jQuery solution: selected radio button value

by Blake Schwendiman on April 20, 2009

The radio button element in an HTML form can be awkward to manage in Javascript. For example, assume the following form:

<form id="radio_form">
  <fieldset>
    <label><input type="radio" name="color" value="red" checked="checked" />Red</label><br />
    <label><input type="radio" name="color" value="yellow" />Yellow</label><br />    
    <label><input type="radio" name="color" value="blue" />Blue</label><br />
    <label><input type="radio" name="color" value="purple" />Purple</label><br />
  </fieldset>
</form>

Using Javascript to determine the currently selected value of the color radio buttons typically involves looping through all of the input elements to find the checked element. As I’ve said before, if you’re looping through the DOM in jQuery, you’re probably doing it wrong.

The jQuery solution for finding the selected radio button’s value looks like this:

[-]?View Code JAVASCRIPT
  var the_value;
  the_value = jQuery('#radio_form input:radio:checked').val();
  alert(the_value);

Test it for yourself (if you’re reading this in a news reader such as Google Reader, you’ll have to go to the original post to test the sample):

Comments:

Comments on this entry are closed.