循环页面元素
$("input[name='status']:checked").each(function(){
console.log($(this).val());
});
循环后台传来的数组数据
$.each(checkboxArray,function(index,value){
console.log(index+"->"+value);
$("input[name='status'][value='"+value+"']").prop("checked",true);
});
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="../js/jquery-3.4.0.min.js" ></script>
<title></title>
</head>
<body>
<input type="checkbox" name="status" value="0"/>状态0
<input type="checkbox" name="status" value="1"/>状态1
<input type="checkbox" name="status" value="2"/>状态2
<input type="checkbox" name="status" value="3"/>状态3
<br />
<input type="button" value="获取多选框的值" onclick="getCheckbox()"/>
<input type="button" value="为复选框赋值" onclick="setCheckbox()" />
</body>
<script>
function getCheckbox(){
$("input[name='status']:checked").each(function(){
console.log($(this).val());
});
}
function setCheckbox(){
var checkboxArray = [0,1,2,3];
$("input[name='status']").prop("checked",false);
$.each(checkboxArray,function(index,value){
console.log(index+"->"+value);
$("input[name='status'][value='"+value+"']").prop("checked",true);
});
}
</script>
</html>