Handling Checkboxes, Radio Buttons and Select Options in jQuery

I figured I’d share how I’ve dealt with some form elements in jQuery. Sometimes you have to look at the docs a few times before you get what you can do, so I think these examples might help someone out there.

Here is how you can handle a change in a dropdown (SELECT tag with an ID that is “layer_image”):

$("#layer_image").change(function()
{
switch ($(this).val())
{
case '0':
$("#radar_image").hide();
break;
default:
$("#radar_image").show();
}
});

Granted I could of used toggle() to do the same thing I figured it was better to show an example using the switch statement.

Here is an example of handling a checkbox (INPUT tag with an name attribute of “option_linkwindow”):

$("input[@name='option_linkwindow']").click(
function()
{
if ($("input[@name='option_linkwindow']").is(":checked"))
$(".feed/ul>li/a").attr("target","_blank");
else
$(".feed/ul>li/a").attr("target","_self");
$(this).blur();
}
);

Here is another example of handling a checkbox (INPUT tag with a name attribute of “option_summary”):

$("#option_summary").change(
function()
{
$("//li/p").toggle();
$("li[p:hidden]").removeClass("expanded");
$("li[p:visible]").addClass("expanded");
$(this).blur();
}
);

And now an example of handling the following radio buttons:

<input type="radio" name="option_layout" value="0" checked="checked" />
<input type="radio" name="option_layout" value="1" />

And now the jQuery code for handling them:

$("input[@name='option_layout']").change(
function()
{
if ($("input[@name='option_layout']:checked").val())
$(".group").toggleClass("group_vert");
else
$(".group").toggleClass("group_vert");
$(this).blur();
}
);

Tags:

16 Comments to “Handling Checkboxes, Radio Buttons and Select Options in jQuery”

  1. chief says:

    Thanks for the examples, but I did just have some problems with using the “change” event with radio buttons in IE. I changed it to “click” and it seems to work better.

  2. Stephen says:

    How do you SET a radio button using jQuery?

  3. blogger says:

    Sample Form

    <form id="myform" name="myform" method="post" action="#">
    <label><input type="radio" name="myradios" value="1" />alpha</label>
    <label><input type="radio" name="myradios" value="2" />beta</label>
    <label><input type="radio" name="myradios" value="3" />gamma</label>
    </form>

    jQuery to maniuplate them

    $("input[@name='myradios']").val("nothing");//changes all to nothing
    $("input[@name='myradios']:nth(2)").val("trident");//change 3rd one
    $("input[@name='myradios']:nth(1)").attr("checked","checked");//make the 2nd one checked

  4. Michael says:

    @chief:
    thanks for your hint with the “click-event”. I had the same problems with “change” in IE. It’s a shame that this bug isn’t fixed in IE7 yet.

  5. Cory says:

    How do you use JQuery to set a selected index of a select box?

  6. blogger says:

    @Cory

    Here is the HTML

    <form id="myform" name="myform" method="post" action="">
    <select name="list" size="3">
    <option value="1" selected="selected">Alpha</option>
    <option value="2">Beta</option>
    <option value="3">Delta</option>
    </select>
    </form>

    Here is the jQuery

    $(document).ready(function() {
    $("#myform select[@name='list'] option[@selected='selected']").removeAttr("selected");//remove any selected items
    $("#myform select[@name='list'] option[@value='2']").attr("selected","selected");//select beta
    $("#myform select[@name='list'] option").removeAttr("selected");//remove any selected items (alternative method)
    $("#myform select[@name='list'] option:eq(3)").attr("selected","selected");//select delta (it finds the third child)
    });

  7. chisler says:

    thanks so much for the examples, they are really helpful as I’m totally new to jquery.

    One thing I havent been able to figure out is how to enable a set of radio buttons if a checkbox is checked.

    I have a big array (in php) that I use to generate a whole list of checkboxes and associated radio buttons (disabled by default). When i check the checkbox I’d like the enable the radio buttons.

    I’m sure its easy with jquery but I havent been able to figure it out now.

    Chisler

  8. blogger says:

    You could make jQuery create the radio buttons when the checkmark is checked and remove it when it is not.

    Here is the HTML

    <form id="myform" name="myform" method="post" action="">
    <label for="name">Name</label>
    <input name="name" id="name" type="text" />
    <fieldset id="newsletters">
    <label><input type="checkbox" name="want_nl" id="want_nl" value="newsletters" />Want newsletters?</label>
    </fieldset>
    </form>

    Here is the jQuery code

    $(document).ready(function(){
    $("input[@name=want_nl]").click(function(){
    if ($(this).is(":checked"))
    {
    $('#newsletters').append('<fieldset id="newsletter_types"></fieldset>');//create fieldset first
    $('#newsletter_types').append('<label><input type="radio" name="nl_type" value="1" />Cars</label>');
    $('#newsletter_types').append('<label><input type="radio" name="nl_type" value="2" />Houses</label>');
    $('#newsletter_types').append('<label><input type="radio" name="nl_type" value="3" />Jobs</label>');
    }
    else
    $("#newsletter_types").remove();
    });
    });

  9. Agata says:

    Thank you, this has helped me a lot, x

  10. blogger says:

    I got a comment from Jagadeesh that submitted some code through my comment form asking why his dropdown select wasn’t firing on the change event and he had a alert() debug in it. What I realized the switch wasn’t testing for string values.

    Here is code for a html page showing a dropdown select that will change divs

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>
    <script type="text/javascript" src="jquery-1.2.3.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $(".propstatus_div").hide();//hide all
    $("#propStatusCd").change(function()
    {
    alert($(this).val());//debug
    $(".propstatus_div").hide();//hide all
    switch ($(this).val())
    {
    case '0':
    $("#inactive").show();
    break;
    case '1':
    $("#active").show();
    break;
    default:
    $("#other").show();
    }
    });
    });
    </script>
    </head>
    <body>
    <form action="" method="get">
    <label>Property Status
    <select name="propStatusCd" id="propStatusCd">
    <option>Select Something</option>
    <option value="0">Inactive</option>
    <option value="1">Active</option>
    <option value="2">Suspended</option>
    <option value="3">Closed</option>
    <option value="4">Pre-Deactive</option>
    <option value="5">Deactive</option>
    <option value="6">Non-Stay</option>
    <option value="7">Test</option>
    <option value="8">Non-Starwood</option>
    </select>
    </label>
    </form>
    <div id="inactive" class="propstatus_div" style="background:#f00;">This div is #inactive</div>
    <div id="active" class="propstatus_div" style="background:#0f0;">This div is #active</div>
    <div id="other" class="propstatus_div" style="background:#00f;">This div is #other</div>
    </body>
    </html>

  11. Đỗ Nam Khánh says:

    Thank you so much. I have a problem with radio button and it resolved by your entry ^^

    Thanks again & best wish for you :)

  12. Flame says:

    Great reference, thanks!

  13. Alexandra says:

    Thanks a lot for the method of getting selected radio button value:

    $(”input[@name='option_layout']:checked”).val()

    :)

  14. Tri' says:

    Thanks your your entry, it very very good, it resolved my prolem.thanks you.

  15. Lacuna says:

    Thanks for this article however does anyone know how to do this through .net? The group name for example is unaccessible as it dynamically changes to an elongated variable at run-time.

    I.E. My previously named ‘LiveOptions’ radio button group name will change to:
    ctl00$ContentPlaceHolder1$TabContainer1$tabLiveOptions$liveDateManagementView$LiveOptions

    ~ Lacuna

  16. Tian says:

    @Lacuna:
    I’ve found the best way to work with RadioButtons and jQuery in .NET (especially if the radiobuttons are embedded in datagrids, repeaters, etc that mangle the client ID’s as per your example) is by using unique class names instead of ID’s. The css class names do not have to occur in your css stylesheet (in fact, they shouldn’t).
    If you’re already using a CSS class for your radiobutton control, then add this new unique class to the existing one. E.g. two rbn’s in the same group:

    Just be aware that as another poster mentioned, .NET renders the asp:RadioButton control as a SPAN with two controls inside it: a radio input and a label. The CssClass property will be applied to the containing SPAN and NOT to the embedded Radio input control.

    So you can have a jQuery click event handler like this:

    $(”.rbnStyle”).click(function() {
    //”this” will point to the SPAN
    var rbnId = $(’#'+this.firstChild.id).attr(’id’);
    alert(”radiobutton id=”+rbnId);
    });

    Note: .change() won’t work because the “.rbnStyle” selector will actually return the SPAN elements (cos they are given the style) and they don’t support a change event.

Leave a Comment

Comments are reviewed before publishing to prevent spam.