<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="firmCategoryId">
<input type="checkbox" name="coffee" value="1">苹果<br />
<input type="checkbox" name="coffee" value="2">香蕉<br />
<input type="checkbox" name="coffee" value="3">袖子<br />
<input type="checkbox" name="coffee" value="4">衣服<br />
<input type="checkbox" name="coffee" value="5">哈哈<br />
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
//设置默认勾选
function checkcategory() {
var checkedArr = [1, 3, 5]
var inputs = document.getElementById("firmCategoryId");
var checkboxInput = inputs.getElementsByTagName('input')
for (var i = 0; i < checkboxInput.length; i++) {
// if (checkedArr.includes(parseInt(checkboxInput[i].value))) {
// checkboxInput[i].checked = true;
// }
if (checkedArr.find(item => item == parseInt(checkboxInput[i].value))) {
checkboxInput[i].checked = true;
}
}
}
checkcategory()
//控制台输出选中的
$('#firmCategoryId').change(function () {
var arr2 = []
var cbox = $("input[name='coffee']:checked")
$.each(cbox, function () {
arr2.push($(this).val())
});
console.log('选中的是',arr2)
})
//这里用的原生JS
var str1 = []
var list = document.getElementsByName("coffee")
for (var i = 0; i < list.length; i++) {
if (list[i].checked == true) {
str1.push(list[i].value)
// console.log(list[i].val()) //不能用.val(), 不是jq对像,需要把js对像转为jq对像 ,$(list[i]).val()
}
}
console.log(str1)
</script>
</html>
JS/jq 实现复选框默认选中
最新推荐文章于 2024-07-12 22:03:30 发布