Thursday, December 18, 2008

Test for radio button value in JavaScript

If you would like to test which radio button is selected in JavaScript you must remember that each button always has a value but only one will have a checked value in the same button group. So to find the selected one you must loop through the group and test the checked value ( see function getSelectedRadioButton() ).


function getSelectedRadioButton(buttonGroup)
{
for ( var i = 0; i < buttonGroup.length; i++)
{
if (buttonGroup[i].checked)
{
return buttonGroup[i].value;
}
}
return 0
}


The function above will return the value assigned to the checked radio button, not the positional value i that it is inside the button group.

Function fnAlertRadioButtonChecked() below will display an alert telling you which radio button was selected. This function can be called from an event in the form.


function fnAlertRadioButtonChecked(form)
{
var j = getSelectedRadioButton(form.myButtonGroupName);

if (j == 'first')
{
alert('The radio button assigned a value of first is checked.');
}
else if (j == 'second')
{
alert('The radio button assigned a value of second is checked.');
}
else if (j == 'third')
{
alert('The radio button assigned a value of third is checked.');
}
else
{
alert('The radio button assigned a value of ' & j & ' is checked.');
}

}