faqts : Computers : Programming : Languages : JavaScript : Forms : Radio buttons

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

45 of 59 people (76%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I find a radio button in a group?
How can I find a radio button in a group by its value?

Mar 20th, 2000 04:10
Martin Honnen,


If you have a group of radio buttons (grouped by the same NAME 
attribute) this group is reflected into JavaScript as an array
  document.formName.radioGroupName
into which the buttons are inserted in source order starting with index 
0 so the first button is
  document.formName.radioGroupName[0]
the second
  document.formName.radioGroupName[1]
and so on.
Radio buttons have a VALUE attribute which (ususally) distinguishes the 
buttons so you could search for a button by its value. The following 
provides a convenience function with some examples:

<HTML>
<HEAD>

<SCRIPT>
function getRadioByValue (radioButtonOrGroup, value) {
  if (!radioButtonOrGroup.length) { // single button
    if (radioButtonOrGroup.value == value)
      return radioButtonOrGroup;
    else
      return null;
  }
  else {
    for (var b = 0; b < radioButtonOrGroup.length; b++)
      if (radioButtonOrGroup[b].value == value)
        return radioButtonOrGroup[b];
    return null;
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
Kibo
<INPUT TYPE="radio" NAME="aRadioGroup" VALUE="Kibo">
Xibo
<INPUT TYPE="radio" NAME="aRadioGroup" VALUE="Xibo">
Maho
<INPUT TYPE="radio" NAME="aRadioGroup" VALUE="Maho">
<BR>
<INPUT TYPE="button" VALUE="check Kibo"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Kibo').checked 
= true;"
>
<INPUT TYPE="button" VALUE="check Xibo"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Xibo').checked 
= true;"
>
<INPUT TYPE="button" VALUE="check Maho"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Maho').checked 
= true;"
>
<BR>
<INPUT TYPE="button" VALUE="uncheck Kibo"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Kibo').checked 
= false;"
>
<INPUT TYPE="button" VALUE="uncheck Xibo"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Xibo').checked 
= false;"
>
<INPUT TYPE="button" VALUE="uncheck Maho"
       ONCLICK="getRadioByValue(this.form.aRadioGroup, 'Maho').checked 
= false;"
>
<BR>
<INPUT TYPE="radio" NAME="aRadio" VALUE="Kibo">
<INPUT TYPE="button" VALUE="check"
       ONCLICK="getRadioByValue(this.form.aRadio, 'Kibo').checked = 
true;"
>
<INPUT TYPE="button" VALUE="uncheck"
       ONCLICK="getRadioByValue(this.form.aRadio, 'Kibo').checked = 
false;"
>
</FORM>
</BODY>
</HTML>