复选框非常有用以获得多个值。
默认情况下,所选复选框值将发布到服务器端的表单上。
但是,如果要在没有表单提交的情况下获取所选复选框的值,则jQuery是最佳选项。
可以使用jQuery轻松获得所选复选框。
在示例代码片段中,我们将展示如何使用jQuery获取所有选定的复选框。
以下代码将使用jQuery按类名获取所有选中的复选框的值。
在以下HTML中,“CHK”类被标记为每个复选框。
此外,按钮放置在复选框下,触发jQuery代码以获取所有选定复选框的值。
<!-- checkboxes --> <div><input type="checkbox" value="1" class="chk"> Value 1</div> <div><input type="checkbox" value="2" class="chk"> Value 2</div> <div><input type="checkbox" value="3" class="chk"> Value 3</div> <div><input type="checkbox" value="4" class="chk"> Value 4</div> <div><input type="checkbox" value="5" class="chk"> Value 5</div> <!-- button to get values --> <input type="button" id="getValue" value="Get Selected Checkboxes Value">
包括jQuery库。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
以下jQuery代码获取所选复选框值。
如果选择,则显示选中的复选框值,否则,将显示警报。
$(document).ready(function(){
$('#getValue').on('click', function(){
//Declare a checkbox array
var chkArray = [];
//Look for all checkboxes that have a specific class and was checked
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
//Join the array separated by the comma
var selected;
selected = chkArray.join(',') ;
//Check if there are selected checkboxes
if(selected.length > 0){
alert("Selected checkboxes value: " + selected);
}else{
alert("Please select at least one checkbox.");
}
});
});
日期:2020-06-02 22:16:06 来源:oir作者:oir
