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

前端 未结 30 3427
花落未央
花落未央 2020-11-21 04:44

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

相关标签:
30条回答
  • 2020-11-21 05:09

    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();
    });
    
    0 讨论(0)
  • 2020-11-21 05:09

    This is some different method to do the same thing:

    $(document).ready(function (){
    
        $('#isAgeSelected').click(function() {
            // $("#txtAge").toggle(this.checked);
    
            // Using a pure CSS selector
            if ($(this.checked)) {
                alert('on check 1');
            };
    
            // Using jQuery's is() method
            if ($(this).is(':checked')) {
                alert('on checked 2');
            };
    
            //  // Using jQuery's filter() method
            if ($(this).filter(':checked')) {
                alert('on checked 3');
            };
        });
    });
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <input type="checkbox" id="isAgeSelected"/>
    <div id="txtAge" style="display:none">Age is something</div>

    0 讨论(0)
  • 2020-11-21 05:12
    $(document).ready(function() {    
        $('#agecheckbox').click(function() {
            if($(this).is(":checked"))
            {
                $('#agetextbox').show();
            } else {
                $('#agetextbox').hide();
            }
        });
    });
    
    0 讨论(0)
  • 2020-11-21 05:14

    I believe you could do this:

    if ($('#isAgeSelected :checked').size() > 0)
    {
        $("#txtAge").show(); 
    } else { 
        $("#txtAge").hide();
    }
    
    0 讨论(0)
  • 2020-11-21 05:15

    I am using this and this is working absolutely fine:

    $("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");
    

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

    0 讨论(0)
  • 2020-11-21 05:16

    This code will help you

    $('#isAgeSelected').click(function(){
       console.log(this.checked);
       if(this.checked == true) {
            $("#txtAge").show();
        } else {
           $("#txtAge").hide();
       }
    });
    
    0 讨论(0)
提交回复
热议问题