Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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> 
like image 614
user737065 Avatar asked Oct 17 '11 09:10

user737065


People also ask

How do you select or deselect all checkboxes using JavaScript?

Code Explanation For the input types as button, we have created one button for selecting the checkboxes where onClick (), the selects () function will be invoked and the other one for deselecting the checkboxes (if selected any/all) where onClick () the deselect () function will be invoked.


1 Answers

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); 
like image 61
James Allardice Avatar answered Oct 31 '22 14:10

James Allardice