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

My question is, how does the write function select all the chceckbox in the form when the entire Id flag starts with some const. string using pure java script (without jquery and other frameworks)? I know how to use this every function from jQuery, but I don’t know how to do this in a pure JS.My form.

<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> 
+6
source share
2 answers

In your case:

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

You can use getElementsByTagName to get all 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 is an example. If you only care about new browsers, you can 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 this. As an answer, you mentioned in your question that when using jQuery you can do this with each . You do not need to use each , since most jQuery methods work with all elements in the corresponding set, so you can only do this on one line:

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

Source: https://habr.com/ru/post/899439/


All Articles