举个例子
<body><input type="checkbox" id="box" checked>123
<script>
var box = document.getElementById('box')
if(box.checked) {
console.log('复选框被选中')
}
</script>
</body>
该案例复选框被选中,所以会出输出'复选框被选中'。checked属性存在会自动转换为bool值true,所以可以if语句做判断。
Hi,一组checkbox有多个对象,需要遍历后选中。假设我们通过form表单来获取所有的checkbox,当然您也可以设置id来获取。代码如下:
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<title>js自动选中checkbox</title>
</head>
<form>
<input type="checkbox" name="testBox" value="1">选择1
<input type="checkbox" name="testBox" value="2">选择2
</form>
<body>
<script language="javascript">
for(var i=0 i<document.forms[0].testBox.length i++){
document.forms[0].testBox[i].checked = true
}
</script>
</body>
</html>
var len=$("input[type=checkbox]:checked()")if(len.length>0){
alert("有选中")
}else{
alert("没有选中")
}