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:

Comments 1-50 of 68 to “Handling Checkboxes, Radio Buttons and Select Options in jQuery”

Pages: 1 2
  1. 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. 2 · Stephen says:

    How do you SET a radio button using jQuery?

  3. 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. 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. 5 · Cory says:

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

  6. 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. 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. 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. 9 · Agata says:

    Thank you, this has helped me a lot, x

  10. 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. 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. 12 · Flame says:

    Great reference, thanks!

  13. 13 · Alexandra says:

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

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

    :)

  14. 14 · Tri' says:

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

  15. 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. 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.

  17. 17 · TEA# says:

    For .NET you can grab it this way, which will get an ID that END WITH your original ID, meaning .NET can prepend whatever it wants on the front and you can get your control by ID.

    $(“span[id*='spnBaleTxt']“)

  18. 18 · blueonyx says:

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

    Thanks again & best wish for you :D

  19. 19 · THE|ODIN says:

    thanks for the tips, some really usefull techniques here

  20. 20 · Taylor says:

    Hi All,

    I’m trying to manually change the value of a select menu to a certain
    option by referencing it’s value.

    I’ve got the three instances I’ve tried (below) which aren’t changing
    the select menu option correctly, in which am having trouble getting
    the correct syntax as to how to SET the value on an “onClick” event.

    + one
    +
    +

    Can someone help me find the correct syntax?

    Thanks!

  21. 21 · robbka says:

    check radio by name:
    if($(“input[@name='your_radio_group_name']“).attr(“checked”)==false) alert(“Please check radio!”)

  22. 22 · elvisparsley says:

    We need more tut like this.
    thanks.

  23. 23 · Danny says:

    Hey,

    Thanks for sharing this.
    I actually reached this page by searching for something similar, only I am looking to capture a change on an input text field.
    The .change() function is only invoked when I alt tab away from the window and then back.

    Can anyone spare a hint?
    (to the blogger – may I suggest adding a “Subscribe to comments” WP plugin?)

  24. 24 · blogger says:

    @Danny
    I would use keypress() and click() and test the input field to see if it did change or not. The reason for the click() is incase someone does a copy and paste with their mouse or if they drag text into the text field.

  25. 25 · Danny says:

    Thanks.

    I used keydown() – thought that the change() event should work, but I guess not.
    Thanks for the click() tip – didnt think of that.

  26. 26 · florin says:

    In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.

  27. 27 · brent says:

    Help!

    I’m new to jquery and need help. I have a best image voting page that has a couple of different categories that submits a form. I want the user to be able to click on the picture instead of the the radio button (might hide the radio button), and just highlight the selected picture, and dim the unselected ones. Please advise. thanks!

  28. 28 · blogger says:

    Brent, take a look at Digg’s submit form (you’ll have to be logged in to see it). You can then test to see when one of the selections is checked or changed and then change the classes of those not checked. Then have the non-selected icons’ alpha set to a lower value or replace with a grayscale image or overlay a white png on top of them to get a dimmed effect.

  29. 29 · brent says:

    hi blogger, that is kind of what i need. I was able to figure out the script.

    $('input').hide();
    //$('li').bind('click change', function() {
    $('li').click( function(){
    $('li').removeClass('selected');
    $(this).addClass('selected');
    $(this).children('input:radio').click();
    });

  30. 30 · zznq says:

    That is real nice. Yet another reason to love jQuery. I mean dang that is great. Thanks for droppin this knowledge.

  31. 31 · Tom says:

    For .net, you can use , with ‘name’ being the ID you specified in . Yes, it makes your code uglier.

  32. 32 · tom says:

    what about changing type of the input on the fly, have tried few ideas – but firebug trowing me error:type property can’t be changed.

    simple login form where user can switch input type from ‘password’ to text and back using checbox

    thx

  33. 33 · Marcello says:

    Hi, i’m trying to use your code to read the selected value of two sets of radio buttons… With just one set everything works perfectly. But if there are two sets then one of them “takes charge” and all the radio buttons return the same value…

    You can see a test case here:
    http://www.kikentai.org/jquery/test.html

    Do you have any idea on why it happens?

    Thanks!
    And thanks for sharing this! :D
    Marcello

  34. 34 · pat says:

    this is extremely helpful. thank you! thinking of this from a different angle is there a way to hide/show input types. for instance, if i have a select with options: text, radio, checkbox and the user selects radio the radio option will appear. similarly, if i they select text, they’ll be able to enter text in the field?

  35. 35 · markd says:

    @Cory & blogger

    you can set an option in a select by assigning to the .val()

    One
    Two
    Three

    Jquery

    $(‘#myselect’).val(“2″);

  36. 36 · hungnd says:

    @Marcello
    Try to change @name= to name=

    :)

  37. 37 · jcyl29 says:

    When using a selector like $(“input[@name='option_linkwindow']“), I get a message in Firefox in the Error console that says

    Error: [Exception... "'Syntax error, unrecognized expression: [@name='option_linkwindow']‘ when calling method: [nsIDOMEventListener::handleEvent]” nsresult: “0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)” location: “” data: no]

    I have the latest version of JQuery, any ideas why I am getting this message?

  38. 38 · blogger says:

    I believe starting with jQuery 1.3 they got rid of requiring the @ in the attributes. So now you just do it like this
    $(“input[name='option_linkwindow']“)

  39. 39 · TrailBlazer says:

    thanks man!!!
    you saved my day once again :)

  40. 40 · quoc says:

    this acticle is good

    thanks alot

  41. 41 · Anonymous says:

    After numerous tutorials, and studying two books on jquery, your article put it together for me. Thanks!

  42. 42 · emptywalls says:

    Thanks for the examples. I’m learning a lot based on them.

  43. 43 · roger says:

    Hi,

    I’m a noob to jquery so I’m wondering if I can do the following: I have 3 radio buttons and when each of them is clicked, I want a different text box to show. In other words, the text boxes are hidden when the radio buttons are not clicked but they are displayed when a particular button is clicked. Is there a way to do this in jquery? Any help is appreciated, thanks.

  44. 44 · Moh says:

    hello, how can i add a new radio button to Asp.RadioButtonList using jquery??

    thanks in advance

  45. 45 · Alvin says:

    if i try to get whether the radio button have been checked by following way

    $(“input[name='radio_btn']“).attr(“checked”)

    even i have select the radio_btn, but it still give me “False” …any clue ?

  46. 46 · washington says:

    Thanks for the examples!!!

    they’re great!

  47. 47 · Rafal says:

    Thanks for this!!! :)

  48. 48 · Steph says:

    Thanks loads for all these examples, exactly what I was looking for!

  49. 49 · Kumares says:

    thks for the example

  50. 50 · kiwi says:

    yo creo que eseria mejor si esto anduviera bien.
    parece que tus comentarios no funcan!

Comments 1-50 of 68

Pages: 1 2

Leave a Comment

Comments are reviewed before publishing to prevent spam.