我有一个字段有 5-6 个复选框(将来会增加更多),该字段名称为 email_notification,这是我在 google 上找到的代码,用于自动检查事件表单上的所有复选框 - 加载时。
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function(checkbox) {
checkbox.checked = true;
});
当我运行代码时,它会自动检查电子邮件通知字段上的所有复选框,还会检查其他字段上的所有复选框。我只想要一个字段自动选中所有复选框。有什么线索可以改变语法吗?谢谢你的帮助。
我对Javascript不熟悉,我已经在谷歌上搜索了一个星期,但没有找到任何线索。
这就是你的答案。我想这可以帮助你解决你的问题。
<p>Select your favorite colors:</p>
<label for="c1"> <input type="checkbox" name="color" value="red" id="c1">Red</label>
<label for="c2"><input type="checkbox" name="color" value="green" id="c2"> Green</label>
<label for="c3"><input type="checkbox" name="color" value="blue" id="c3">Blue</label>
<p>
<button id="button2">check/uncheck all</button>
<script>
// check function
function check(checked = true){
const checkboxes = document.querySelectorAll('input[name="color"]');
checkboxes.forEach(checkbox =>{
checkbox.checked = checked;
})
}
// check all checkboxes
function checkAll(){
check();
this.onclick = uncheckAll;
}
// uncheck all
function uncheckAll(){
check(false);
this.onclick = checkAll;
}
const button2 = document.querySelector('#button2');
button2.onclick = checkAll;
</script>