Marty Wallace
Marty Wallace

Reputation: 35734

Get radio button value by name in group with javascript

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

Answers (1)

laaposto
laaposto

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);
}

DEMO

Upvotes: 8

Related Questions