如何js验证复选框选中

JavaScript07

如何js验证复选框选中,第1张

建议取标签name: <input type="checkbox" id="ck1" name="myCheckBox" value="1"/><input type="checkbox" id="ck2" name="myCheckBox" value="2"/><input type="checkbox" id="ck3" name="myCheckBox" value="3"/><script>//取name为myCheckBox的对象数组 var chkArray= document.getElementsByName('myCheckBox' )//循环取得的数组,输出选中按钮的值 for(var i=0i<chkArray.lengthi++) if(chkArray[i].checked){ alert("选中的是"+chkArray[i].value)} } </script>

举个例子

<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语句做判断。