Friday, May 25, 2012

Check checkbox checked property using jQuery


I need to check the checked property of a checkbox and perform the action based on the checked property using jQuery .



For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.



But the following code gives false as by default:




if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
}
else
{
$("#txtAge").hide();
}



Did I miss anything here?


Source: Tips4all

19 comments:

  1. Try this:

    if ($('#isAgeSelected').is(':checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); }


    You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:

    $('#isAgeSelected').is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();


    EDIT (14 months later): There's a much prettier way to do this, using toggle:

    $('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
    });

    <input type="checkbox" id="isAgeSelected"/>
    <div id="txtAge" style="display:none">Age is something</div>​


    Demo: http://jsfiddle.net/5udtC/

    ReplyDelete
  2. Use Jquery is() function

    if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();
    else
    $("#txtAge").hide();

    ReplyDelete
  3. This worked for me.

    $get("isAgeSelected ").checked == true


    where isAgeSelected is the id of the control.

    Also @karim79's answer works fine. I am not sure what i missed at the time i tested it.

    Note, this is answer uses MicrosoftAjax, not jQuery

    ReplyDelete
  4. Using jQuery > 1.6

    <input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

    // traditional attr
    $('#checkMeOut').attr('checked'); // "checked"
    // new property method
    $('#checkMeOut').prop('checked'); // true


    Using the new property method:

    if($('#checkMeOut').prop('checked')) {
    // something when checked
    } else {
    // something else when not
    }

    ReplyDelete
  5. I am using this and this is working absolutely fine:

    if($("#checkkBoxId").attr("checked")==true)
    {
    alert("Checked");
    }
    else
    {
    alert("Unchecked");
    }


    Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.

    ReplyDelete
  6. I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.

    var ageCheckbox = document.getElementById('isAgeSelected');
    var ageInput = document.getElementById('txtAge');

    // Just because of IE <333
    ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
    };


    First you get both elements by their ID. Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.

    Here is a fiddle for you to test it.

    Addendum

    If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.

    elem.style.display = this.checked ? 'inline' : 'none';


    Slower but cross-browser compatible.

    ReplyDelete
  7. Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself! Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed(independent of how it's done so).

    $('#isAgeSelected').bind('change', function () {

    if ($(this).is(':checked'))
    $("#txtAge").show();
    else
    $("#txtAge").hide();

    });

    ReplyDelete
  8. Since jQuery 1.6, The behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element's checked state. Instead, you should use jQuery.prop():

    $("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // for checked attribute it returns true/false;
    // return value changes with checkbox state
    );


    Two other possibilities are:

    $("#txtAge").get(0).checked
    $("#txtAge").is(":checked")

    ReplyDelete
  9. $(selector).attr('checked') !== undefined


    This returns true if the input is checked and false if it not.

    ReplyDelete
  10. I believe you could do this:

    if ($('#isAgeSelected :checked').size() > 0)
    {
    $("#txtAge").show();
    } else {
    $("#txtAge").hide();
    }

    ReplyDelete
  11. I ran in to the exact same issue. I have an ASP.NET checkbox

    <asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />


    In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.

    if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
    { ... } else { ... }


    I'm sure you can also use the ID instead of the CssClass,

    if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
    { ... } else { ... }


    I hope this helps you.

    ReplyDelete
  12. I verified in Firefox 9.0.1 that the following works for catching the state of a checkbox post change:

    $("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';
    alert(value);
    });

    ReplyDelete
  13. My way of doing this is:

    if ( $("#checkbox:checked").length ) {

    alert("checkbox is checked");

    } else {

    alert("checkbox is not checked");

    }

    ReplyDelete
  14. this works for me,

    /* isAgeSelected being id for checkbox */

    $("#isAgeSelected").click(function(){
    $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
    });

    ReplyDelete
  15. Here's an example that includes initialising the show/hide to match the state of the checkbox when the page loads; taking account of the fact that firefox remembers the state of checkboxes when you refresh the page, but won't remember the state of the shown/hidden elements.

    $(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
    });


    (with help from other answers on this question)

    ReplyDelete
  16. I was having the same problem and none of the posted solutions seemed to work and then I found out that it's because ASP.NET renders the CheckBox control as a SPAN with INPUT inside, so the CheckBox ID is actually an ID of a SPAN, not an INPUT, so you should use:

    $('#isAgeSelected input')


    rather than

    $('#isAgeSelected')


    and then all methods listed above should work.

    ReplyDelete
  17. I had the same problem, and got it fixed using @karim79 answer.
    But I wanted to go further so that it would do this when the checkbox state was changed again. So here's my example, it might help someone

    http://jsfiddle.net/shano/bK8EC/26/

    ReplyDelete
  18. if ($("#checkkBoxId").is(':checked') == true) {
    alert("Checked");
    }
    else {
    alert("Unchecked");
    }

    ReplyDelete
  19. if($('#isAgeSelected ').attr('checked')){
    $("#txtAge").show();
    }
    else {
    $("#txtAge").hide();
    }


    Check out this will work definitely...

    I made below code in my form

    if($('#yesAttendedWorkshop').attr('checked')){
    $("#workshopinfo").show();
    }
    else if($('#notAttendedWorkshop').attr('checked')){
    $("#workshopinfo").hide();
    $(':input','#workshopinfo').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected');
    $('#workshopinfo input:checkbox').removeAttr('checked');
    $('#workshopinfo input:text').val('');
    }
    else {
    $("#workshopinfo").hide();
    alert("It seems that your profile is not up-to-date. \n\n Please complete your profile ...");
    }

    ReplyDelete