user737065
user737065

Reputation: 397

How can I select all checkboxes from a form using pure JavaScript (without JS frameworks)?

I have question, how write function to select all chceckbox on form, when all checkbox Id start from some const. string, using pure java script (without jquery and other frameworks) ? I know how do it using each function from JQuery, but I dont have any idea hwo do it in pure JS.My form ex.

    <form id="myId" name="myForm">
<input type="checkbox"  id="lang_1" value="de"/> DE
<input type="checkbox"  id="lang_2" value="us"/> US
<input type="checkbox"  id="lang_3" value="ru"/> RU
<input type="button" onclick="Select();"  value="Select all"/>
</form>

Upvotes: 26

Views: 53831

Answers (3)

Gio
Gio

Reputation: 46

Updated version for modern browsers that support forEach in NodeList:

let inputs = document.getElementsByTagName("input");
inputs.forEach(i => i.click() )

Upvotes: 1

gregseth
gregseth

Reputation: 13408

In your case:

for (i = 1; i<3; i++) {
  document.getElementById('lang_'+i).checked = true;
}

Upvotes: 4

James Allardice
James Allardice

Reputation: 165951

You could use getElementsByTagName to get all the input elements:

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type == "checkbox") {
        inputs[i].checked = true; 
    }  
}

Here's an example of that. If you only care about newer browsers, you could use querySelectorAll:

var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
    inputs[i].checked = true;   
}

And an example of that one. As an aside, you mentioned in your question that when using jQuery you could do this using each. You don't need to use each, as most jQuery methods operate on all elements in the matched set, so you can do it in just one line:

$("input[type='checkbox']").prop("checked", true);

Upvotes: 87

Related Questions