Monday 22 September 2008

Javascript: Read Selected Value of a Radio Group

When you first approach reading the value of a radio group input, you may be fooled into assuming it would be similar to reading a text input, IE "document.myForm.myInput.value", however radio groups are not so straight forward.

To get the value you need to loop through the radio group elements to find which one is checked, then get the value for that element.

This example contains the getRadioValue function which can be added to any page, just pass the object reference of the radio group, as the parameter.

It's also an example of how to add a radio to your form.

<html>

<head>
<script>
function getRadioValue(radioObj)
{
var radioValue = 'undefined';
for (i=0; i<radioObj.length; i++)
{
if(radioObj[i].checked==true)
{
radioValue = radioObj[i].value;
break;
}
}
return radioValue;
}
</script>
</head>

<body>

<h1>Get Radio Group Value</h1>

<form name="myForm">

<input type="radio" name="myRadioGroup" value="R">Red</input> <br/>
<input type="radio" name="myRadioGroup" value="G">Green</input> <br/>
<input type="radio" name="myRadioGroup" value="B">Blue</input> <br/>
<br/>
<input type="button" onclick="alert(getRadioValue(document.myForm.myRadioGroup));" value="Test"/>

</form>

</body>

</html>

Value Got.

No comments: