Getting value of selected Radio group

P

Peter

Hi all,

Sorry if this is an obvious/common question, but I'm trying to get the
value of a radio button using JavaScript.

Where I can easily get the value of a text field:

document.myform.myfield.value

how do I get the value of the *selected* radio button? E.g. given:

<input type="radio" name="mygroup" value="1">
<input type="radio" name="mygroup" value="2">

using:

document.myform.mygroup.value

doesn't work as there are two (in this case) radio buttons with the same
name!

Thanks in advance!

Peter.
 
N

N Clements

Try using something like the following in your javascript function:


var val = 0;

for( i = 0; i < document.myform.mygroup.length; i++ )
{
if( document.myform.mygroup.checked == true )
val = document.myform.mygroup.value;
}
alert( "val = " + val );

Hope that helps.

N. Clements
Brainbench MVP for _Javascript
www.brainbench.com
(e-mail address removed).242.mailshell.com
Remove 2nd through 4th spam to reply.
 
P

Peter

N said:
Try using something like the following in your javascript function:


var val = 0;

for( i = 0; i < document.myform.mygroup.length; i++ )
{
if( document.myform.mygroup.checked == true )
val = document.myform.mygroup.value;
}
alert( "val = " + val );

Hope that helps.


Thanks loads - thats great!!
:)
 
S

Steve van Dongen

N said:
Try using something like the following in your javascript function:


var val = 0;

for( i = 0; i < document.myform.mygroup.length; i++ )
{
if( document.myform.mygroup.checked == true ) {
val = document.myform.mygroup.value;

break; // stop searching as soon as one is found
}
Thanks loads - thats great!!
:)

Just add the break statement like above to reduce the amount of work
being done.

Regards,
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top