Reputation: 35734
Say i have a radio button group like so:
<input type="radio" name="mygroup" value="Hello 1" />Hello 1<br/>
<input type="radio" name="mygroup" value="Hello 2" />Hello 2<br/>
<input type="radio" name="mygroup" value="Hello 3" />Hello 3<br/>
Can i access one of these elements based on the index in the group?
For example I would like to target the second element?
How can this be done in javascript?
Upvotes: 2
Views: 233
Reputation: 12213
You can use getElementsByName
It returns an array of HTML elements. Then you can loop through the returned array by indexing and get the element you want.
So in your question (target the second element) you should use:
var radios = document.getElementsByName('mygroup');
radios[1].value;
And in a more generic way you should use:
var radios = document.getElementsByName('mygroup');
for(i=0;i<radios.length;i++){
console.log(radios[i].value);
}
Upvotes: 8