How do you change an HTML radiobutton selection from Javascript?

27,573

If you set the "checked" property to true on one radio button, the other button with the same name is automatically unchecked.

Thus,

document.getElementById('buttonX').checked = true;

will cause "buttonY" to be unchecked if the HTML looks like:

<input type='radio' id='buttonX' name='fred' value='X'>
<input type='radio' id='buttonY' name='fred' value='Y' checked>

edit Remember that "radio buttons" have that name because on old radios (not necessarily older than me) the station preset buttons were mechanically inter-linked such that exactly one button was pressed at all times. Fiddling with the buttons to get them all to be un-pressed was a fun but risky pastime, as most adults didn't appreciate the aesthetic appeal of a row of un-pressed radio buttons all neatly aligned.

Share:
27,573
Giffyguy
Author by

Giffyguy

I enjoy writing hardcore OO data-structures in native C++.

Updated on August 17, 2022

Comments

  • Giffyguy
    Giffyguy over 1 year

    I need to select an HTML radiobutton (deselecting any previously selected radiobutton) on my form, from within Javascript.

    How is this accomplished?

  • Quentin
    Quentin almost 14 years
    Property, not attribute. If you were setting the attribute then the value would be checked, not true.
  • Pointy
    Pointy almost 14 years
    Well OK; property, attribute, I guess it makes a difference.