[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

How do I check whether a checkbox is checked in jQuery?

  • This topic is empty.
Viewing 15 posts - 1 through 15 (of 31 total)
  • Author
    Posts
  • #8999
    David Hoang
    Keymaster

    I need to check the checked property of a checkbox and perform an 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 returns false by default:

    if ($('#isAgeSelected').attr('checked')) {
      $("#txtAge").show();
    } else {
      $("#txtAge").hide();
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" id="isAgeSelected"/>
    <div id="txtAge" style="display:none">
      Age is selected
    </div>

    How do I successfully query the checked property?

    #9023
    David Hoang
    Keymaster

    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.

    #9024
    David Hoang
    Keymaster

    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)

    #9005
    David Hoang
    Keymaster
    if( undefined == $('#isAgeSelected').attr('checked') ) {
        $("#txtAge").hide();
    } else {
        $("#txtAge").show();
    }
    
    #9013
    David Hoang
    Keymaster
    if( undefined == $('#isAgeSelected').attr('checked') ) {
        $("#txtAge").hide();
    } else {
        $("#txtAge").show();
    }
    
    #9020
    David Hoang
    Keymaster

    Use:

    $(this).toggle($("input:checkbox", $(this))[0].checked);
    

    When you are selecting out of context, remember you need the [0] to access the checkbox.

    #9021
    David Hoang
    Keymaster

    This was my workaround:

    $('#vcGoButton').click(function () {
        var buttonStatus = $('#vcChangeLocation').prop('checked');
        console.log("Status is " + buttonStatus);
        if (buttonStatus) {
            var address = $('#vcNewLocation').val();
            var cabNumber = $('#vcVehicleNumber').val();
            $.get('postCabLocation.php',
                  {address: address, cabNumber: cabNumber},
                  function(data) {
                      console.log("Changed vehicle " + cabNumber + " location to " + address );
                  });
        }
        else {
            console.log("VC go button clicked, but no location action");
        }
    });
    
    #9026
    David Hoang
    Keymaster

    This is the minimal amount of code I think I needed to do something like this effectively. I found this method to be useful; it returns an array of the check boxes that are checked and then you can use their value (this solution uses jQuery):

    // This is how you get them
    var output = "";
    var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
    if(checkedBoxes.length <= 0) {
        alert('Please select check boxes');
        return false;
    };
    
    // And this is how you use them:
    checkedBoxes.each(function() {
        output +=  this.value + ", ";
    };
    

    Printing “output” will give you a comma-separated list of your values.

    #9028
    David Hoang
    Keymaster

    The checked attribute of an input type="checkbox" is mapped with the defaultChecked property, not with the checked property.

    So when doing something in a page when a checkbox is checked on uncheked, use the prop() method instead. It fetches the property value and changes as the state of the checkbox changes.

    Using attr() or getAttribute(in pure JavaScript) in these cases are not the proper way of doing things.

    if elem is the concerned checkbox then do something like this to fetch the value:

    elem.checked
    

    or

    $(elem).prop('checked')
    
    #9022
    David Hoang
    Keymaster

    Setter:

    $("#chkmyElement")[0].checked = true;
    

    Getter:

    if($("#chkmyElement")[0].checked) {
       alert("enabled");
    } else {
       alert("disabled");
    }
    
    #9029
    David Hoang
    Keymaster

    Automated

    $(document).ready(function()
    {
        $('#isAgeSelected').change(function()
        {
            alert( 'value =' + $('#chkSelect').attr('checked') );
        });
    });
    

    HTML

    <b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>
    
    <br/><br/>
    
    <input type="button" id="btnCheck" value="check" />
    

    jQuery

    $(document).ready(function()
    {
        $('#btnCheck').click(function()
        {
            var isChecked = $('#isAgeSelected').attr('checked');
    
            if (isChecked == 'checked')
                alert('check-box is checked');
            else
                alert('check-box is not checked');
        })
    });
    

    Ajax

    function check()
    {
        if (isAgeSelected())
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    }
    
    function isAgeSelected()
    {
        return ($get("isAgeSelected").checked == true);
    }
    
    #9017
    David Hoang
    Keymaster

    I would actually prefere the change event.

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

    Demo Fiddle

    #9002
    David Hoang
    Keymaster

    In case if you need to use CSS class as jQuery selector you can do following:

    $(document).ready(function () {
            $('.myOptionCheckbox').change(function () {            
                if ($(this).prop('checked') == true) {
                    console.log("checked");           
                }
                else {
                    console.log("unchecked");                
                }
            });
        });
    

    It works fine for checkboxes and radioboxes as well.

    #9000
    David Hoang
    Keymaster

    $("#isAgeSelected").prop('checked', true);

    #9018
    David Hoang
    Keymaster

    A selector returns multiple objects, and it must take the first item in the array:

    // Collection
    var chckremember = $("#chckremember");
    
    
    // Result boolen
    var ischecked=chckremember[0].checked;
    
Viewing 15 posts - 1 through 15 (of 31 total)
  • You must be logged in to reply to this topic.