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.
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.
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.
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.
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
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