我有以下代码。我想检查按钮单击上的所有复选框。如何仅使用JavaScript执行此操作?
<div id="blocked_list_add_website_help_text">
<button type="button" id="blockSelectAll" class="secondary">Select All</button>
</div>
<input type="checkbox" value="box1" />Box1
<input type="checkbox" value="box2" />Box2
<input type="checkbox" value="box3" />Box3
答案 0 :(得分:3)
Pure JS:
document.getElementById("blockSelectAll").onclick = function() {
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = true;
}
}
}
答案 1 :(得分:3)
document.getElementById("blockSelectAll").onclick = function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]');
for(var i=0; i<checkboxes.length; i++){
checkboxes[i].checked = true;
}
};
答案 2 :(得分:1)
是的,你可以试试这个
<强> HTML 强>
<button type="button" id="blockSelectAll" onclick="checkAll()" class="secondary">Select All</button>
<强>的JavaScript 强>
function checkAll() {
var checkboxes = document.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].setAttribute('checked', true) // Or inputs[i].checked = true;
}
}
}
答案 3 :(得分:0)
<script language="JavaScript">
function checker() {
checkboxes = document.getElementsByTagName('input');
for each(var checkbox in checkboxes)
checkbox.checked = true;
}
</script>
<div id="blocked_list_add_website_help_text">
<button type="button" id="blockSelectAll" class="secondary" onclick=checker() >Select All</button>
</div>
<input type="checkbox" value="box1" />Box1
<input type="checkbox" value="box2" />Box2
<input type="checkbox" value="box3" />Box3