0

I have the following code. I want to check all the check boxes on button click. How do I do this using JavaScript only?

<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 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

Yes you can just try this

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

1 Comment

No need to create a new Array() first
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.