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

前端 未结 30 3513
花落未央
花落未央 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 04:56
    $(selector).attr('checked') !== undefined
    

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

    0 讨论(0)
  • 2020-11-21 04:57

    You can use:

      if(document.getElementById('isAgeSelected').checked)
        $("#txtAge").show();  
      else
        $("#txtAge").hide();
    

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

    Both of them should work.

    0 讨论(0)
  • 2020-11-21 04:57

    Toggle: 0/1 or else

    <input type="checkbox" id="nolunch" />
    <input id="checklunch />"
    
        $('#nolunch').change(function () {
        if ($(this).is(':checked')) {
            $('#checklunch').val('1');
        };
        if ($(this).is(':checked') == false) {
            $('#checklunch').val('0');
        };
    });
    
    0 讨论(0)
  • 2020-11-21 04:58

    jQuery 1.6+

    $('#isAgeSelected').prop('checked')
    

    jQuery 1.5 and below

    $('#isAgeSelected').attr('checked')
    

    Any version of jQuery

    // Assuming an event handler on a checkbox
    if (this.checked)
    

    All credit goes to Xian.

    0 讨论(0)
  • 2020-11-21 04:58

    Use:

    <input type="checkbox" id="abc" value="UDB">UDB
    <input type="checkbox" id="abc" value="Prasad">Prasad
    
    $('input#abc').click(function(){
      if($(this).is(':checked'))
      {
        var checkedOne=$(this).val()
        alert(checkedOne);
    
        // Do some other action
      }
    })
    

    This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.

    0 讨论(0)
  • 2020-11-21 04:58

    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.

    0 讨论(0)
提交回复
热议问题