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>
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With