Vanilla javascript select by name

So, I have this problem when I need to set a value for a checkbox depending on some variables.

The problem is that I came across the following HTML naming convention with which I will work:

<input id="jc_1" type="checkbox" name="jc[1]"> <input id="jc_2" type="checkbox" name="jc[2]"> <input id="jc_3" type="checkbox" name="jc[3]"> <input id="jc_4" type="checkbox" name="jc[4]"> 

To decide which input to select, I would usually do:

 document.getElementsByName('jc') 

Then skip all of them and decide which one to check, the problem is that I really do not know how to deal with this situation in these specific conditions.

I cannot use jQuery, and I cannot change my HTML markup.

+5
source share
3 answers

You can use starting with the attribute selector with querySelectorAll :

 var jcList = document.querySelectorAll("[name^=jc\\[]"); 

Beware that this may correspond to the following elements:

 <input id="jc_1" type="checkbox" name="jc[0][0]"> 

This may not be a problem for your specific requirements.

+7
source

Too bad, you cannot change the markup.

You can do something like ..

 for(var i = 0; i<numberOfCheckboxes.length; i++){ document.getElementsByName('jc['+i+']'); } 

But this is really awful code. And that assumes you know numberOfCheckboxes.

+1
source

document.getElementsByName() returns an array (even if it contains only one element). You just need to reference the element [0] in the array of your choice, for example, document.getElementsByName('jc[1]')[0]

 document.getElementsByName('jc[1]')[0].setAttribute('checked','checked'); 

Demo

+1
source

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


All Articles