Selecting radio button in JavaScript with jQuery

I’m learning jQuery, and really like all the endless additional features (not to mention the ease of writing code!) it brings to JavaScript. But for a newbie some things take time to sink in, especially since the concept of jQuery is a bit different from vanilla JavaScript.

It took me couple of hours to figure out the following two lines to control default selection of radio buttons in a form (I knew how it’s done in plain JavaScript, of course, but it was the jQuery format that was something new to figure out). Setting the radio button attribute isn’t enough; the value needs to be set separately. I might write a simple helper plugin for jQuery later once I become more familiar with it so that setting the attribute automatically sets the corresponding value to the radio group.

$("input[@name='us_edition']").val("both");
$("#us_edition_both").attr("checked", "checked"); 

That piece of code selects the "us_edition_both" (with value "both") radio button in my form:

<input name="us_edition" type="radio" id="us_edition_both" value="both" \ 
onClick="show_us_mailing();" checked="checked"> 
<input name="us_edition" type="radio" id="us_edition_digi" value="digi" \ 
onClick="hide_us_mailing();">

Of course it shouldn’t have been this difficult to figure out and, of course, it isn’t.  A month from now I’ll snicker at myself having spent more than two hours figuring out how to do this. :D

4 Responses to “Selecting radio button in JavaScript with jQuery”


  1. 1 Arjan

    And to get the selected value:

    var selected = $(”input[@name='us_edition']:checked”).val();

    By the way: I doubt one needs to set the value; I think

    $(”#us_edition_both”).attr(”checked”, “checked”);

    is sufficient to make the browser do the rest.

  2. 2 gorenje

    I tried this out but couldn’t get it working. I ended up using the form plugin from jquery –> http://malsup.com/jquery/form/#download

    The plugin works a treat :-)

  3. 3 Etienne Posthumus

    And I was looking and looking and looking, and finally found how to set a radiobutton to checked with jQuery on your blog. Thanks for sharing, cheers

  4. 4 jain

    That was what i was looking for !!

Leave a Reply