Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla javascript select by name

Tags:

javascript

So I have this issue where I need to set a value to a checkbox depending on some variables.

The problem is that I encountered the next naming convention on the HTML I'll be working with:

<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 normally do:

document.getElementsByName('jc')

Then loop through all of them and decide which one to check, the problem here is that I don't really know how to handle this situation in these specific conditions.

I can't use JQuery and I can't change my HTML markup.

like image 262
Mandi Avatar asked Jan 20 '15 15:01

Mandi


People also ask

How to select by name in js?

JavaScript getElementsByName() example How it works: First, select the submit button by its id btnRate using the getElementById() method. Second, listen to the click event of the submit button. Third, get all the radio buttons using the getElementsByName() and show the selected value in the output element.


3 Answers

You could use the begins with attribute selector with querySelectorAll:

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

Beware though that this could match the following elements:

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

Which may not be a problem for your particular requirements.

like image 53
CodingIntrigue Avatar answered Sep 21 '22 22:09

CodingIntrigue


Too bad you can't change the markup.

You could do something like..

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

But this is really terrible code. And that's assuming that you know numberOfCheckboxes.

like image 35
Valentin Roudge Avatar answered Sep 17 '22 22:09

Valentin Roudge


document.getElementsByName() returns an array (even if it just contains one element. You just need to reference the [0] element in your selected array like this document.getElementsByName('jc[1]')[0]

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

DEMO

like image 36
JRulle Avatar answered Sep 18 '22 22:09

JRulle