使用JavaScript选择所有按钮

时间:2014-04-22 12:55:20

标签: javascript html

我有以下代码。我想检查按钮单击上的所有复选框。如何仅使用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

4 个答案:

答案 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;
        }
    }
}

Working fiddle

答案 1 :(得分:3)

使用document.querySelectorAll

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;
         }
     }
 }

Fiddle Demo

答案 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