JavaEar 专注于收集分享传播有价值的技术资料

如何检查jQuery中是否选中了复选框? (How to check whether a checkbox is checked in jQuery?)

问题描述


英文原文

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();
}}

How do I successfully query the checked property?


中文翻译

我需要检查复选框的 checked 属性,并使用jQuery基于checked属性执行操作。

例如,如果选中年龄复选框,则需要显示一个文本框以输入年龄,否则隐藏文本框。

但是以下代码默认返回 false

  if($('#isAgeSelected')。attr('checked'))
{
    $( " #txtAge" )显示()。
}
其他
{
    $( " #txtAge" )隐藏()。
}}
 

如何成功查询 checked 属性?

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();
}}

How do I successfully query the checked property?

我需要检查复选框的 checked 属性,并使用jQuery基于checked属性执行操作。

例如,如果选中年龄复选框,则需要显示一个文本框以输入年龄,否则隐藏文本框。

但是以下代码默认返回 false

  if($('#isAgeSelected')。attr('checked'))
{
    $( " #txtAge" )显示()。
}
其他
{
    $( " #txtAge" )隐藏()。
}}
 

如何成功查询 checked 属性?

30个回答

    最佳答案

  1. 英文原文

    How do I successfully query the checked property?

    The checked property of a checkbox DOM element will give you the checked state of the element.

    Given your existing code, you could therefore do this:

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

    However, there's a much prettier way to do this, using toggle:

    $('#isAgeSelected').click(function() {
        $("#txtAge").toggle(this.checked);
    });
    <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 something</div>


    中文翻译

      

    如何成功查询已检查的属性?

    复选框DOM元素的 checked 属性将为您提供元素的 checked 状态。

    鉴于您现有的代码,您可以这样做:

      if(document.getElementById('isAgeSelected')。checked){
        $( " #txtAge" )显示()。
    } else {
        $( " #txtAge" )隐藏()。
    }
     

    然而,使用 toggle

      $('#isAgeSelected')。click(function(){
        $( " #txtAge" )来回切换(this.checked);
    });  
     &lt; script src =" https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min的.js" &GT;&LT; /脚本&GT;
    &lt; input type =" checkbox" id =" isAgeSelected" /&gt;
    &lt; div id =" txtAge" style =" display:none" &gt;年龄是&lt; / div&gt;  

    How do I successfully query the checked property?

    The checked property of a checkbox DOM element will give you the checked state of the element.

    Given your existing code, you could therefore do this:

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

    However, there's a much prettier way to do this, using toggle:

    $('#isAgeSelected').click(function() {
        $("#txtAge").toggle(this.checked);
    });
    <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 something</div>

      

    如何成功查询已检查的属性?

    复选框DOM元素的 checked 属性将为您提供元素的 checked 状态。

    鉴于您现有的代码,您可以这样做:

      if(document.getElementById('isAgeSelected')。checked){
        $( " #txtAge" )显示()。
    } else {
        $( " #txtAge" )隐藏()。
    }
     

    然而,使用 toggle

      $('#isAgeSelected')。click(function(){
        $( " #txtAge" )来回切换(this.checked);
    });  
     &lt; script src =" https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min的.js" &GT;&LT; /脚本&GT;
    &lt; input type =" checkbox" id =" isAgeSelected" /&gt;
    &lt; div id =" txtAge" style =" display:none" &gt;年龄是&lt; / div&gt;  

  2. 参考答案2
  3. Use jQuery's is() function:

    if($("#isAgeSelected").is(':checked'))
        $("#txtAge").show();  // checked
    else
        $("#txtAge").hide();  // unchecked
    
  4. 参考答案3
  5. 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
    }
    
  6. 参考答案4
  7. 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.

  8. 参考答案5
  9. 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.

  10. 参考答案6
  11. 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")
    
  12. 参考答案7
  13. Use:

    <input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
    
    $("#planned_checked").change(function() {
        if($(this).prop('checked') == true) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
    

        $("#planned_checked").change(function() {
            if($(this).prop('checked') == true) {
                alert("Checked Box Selected");
            } else {
                alert("Checked Box deselect");
            }
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

  14. 参考答案8
  15. 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 Microsoft Ajax, not jQuery

  16. 参考答案9
  17. If you are using an updated version of jquery, you must go for .prop method to resolve your issue:

    $('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. So do as given below.

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

    Hope it helps :)- Thanks.

  18. 参考答案10
  19. 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();
    });
    
  20. 参考答案11
  21. 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.

  22. 参考答案12
  23. I believe you could do this:

    if ($('#isAgeSelected :checked').size() > 0)
    {
        $("#txtAge").show(); 
    } else { 
        $("#txtAge").hide();
    }
    
  24. 参考答案13
  25. 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.

  26. 参考答案14
  27. This works for me:

    /* isAgeSelected being id for checkbox */
    
    $("#isAgeSelected").click(function(){
      $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
    });
    
  28. 参考答案15
  29. There are many ways to check if a checkbox is checked or not:

    Way to check using jQuery

    if (elem.checked)
    if ($(elem).prop("checked"))
    if ($(elem).is(":checked"))
    if ($(elem).attr('checked'))
    

    Check example or also document:

  30. 参考答案16
  31. My way of doing this is:

    if ( $("#checkbox:checked").length ) {       
        alert("checkbox is checked");
    } else {
        alert("checkbox is not checked");
    }
    
  32. 参考答案17
  33. $(selector).attr('checked') !== undefined
    

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

  34. 参考答案18
  35. $(document).ready(function() {    
        $('#agecheckbox').click(function() {
            if($(this).is(":checked"))
            {
                $('#agetextbox').show();
            } else {
                $('#agetextbox').hide();
            }
        });
    });
    
  36. 参考答案19
  37. You can use this code:

    $('#isAgeSelected').click(function(){
       console.log(this.checked);
       if(this.checked == true) {
            $("#txtAge").show();
        } else {
           $("#txtAge").hide();
       }
    });
    
  38. 参考答案20
  39. Use this:

    if ($('input[name="salary_in.Basic"]:checked').length > 0)
    

    The length is greater than zero if the checkbox is checked.

  40. 参考答案21
  41. 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>

  42. 参考答案22
  43. 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.

  44. 参考答案23
  45. 1) If your HTML markup is:

    <input type="checkbox"  />
    

    attr used:

    $(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set
    

    If prop is used:

    $(element).prop("checked"); // Will give you false whether or not initial value is set
    

    2) If your HTML markup is:

     <input type="checkbox"  checked="checked" />// May be like this also  checked="true"
    

    attr used:

    $(element).attr("checked") // Will return checked whether it is checked="true"
    

    Prop used:

    $(element).prop("checked") // Will return true whether checked="checked"
    
  46. 参考答案24
  47. The top answer didn't do it for me. This did though:

    <script type="text/javascript">
        $(document).ready(function(){
    
            $("#li_13").click(function(){
                if($("#agree").attr('checked')){
                    $("#saveForm").fadeIn();
                }
                else
                {
                    $("#saveForm").fadeOut();
                }
            });
        });
    </script>
    

    Basically when the element #li_13 is clicked, it checks if the element # agree (which is the checkbox) is checked by using the .attr('checked') function. If it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.

  48. 参考答案25
  49. 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');
        };
    });
    
  50. 参考答案26
  51. This example is for button.

    Try the following:

    <input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>
    
    <input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
    <input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
    <input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>
    
    
    $('#remove').attr('disabled', 'disabled'); 
    
    $(document).ready(function() {  
    
        $('.cb-element').click(function() {
    
            if($(this).prop('checked'))
            {
                $('#remove').attr('disabled', false);
            }
            else
            {
                $('#remove').attr('disabled', true);
            }
        });   
    
        $('.check:button').click(function()
    {
        var checked = !$(this).data('checked');
        $('input:checkbox').prop('checked', checked);
        $(this).data('checked', checked);
    
        if(checked == true)
        {
            $(this).val('Uncheck All');
             $('#remove').attr('disabled', false);
        }
    
        else if(checked == false)
        {
            $(this).val('Check All');
            $('#remove').attr('disabled', true);
        }
    });
    });
    
  52. 参考答案27
  53. Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

    Assuming that you have the following HTML:

    <label for="show_textbox">Show Textbox</label>
    <input id="show_textbox" type="checkbox" />
    <input type="text" />
    

    You can use the following CSS to achieve the desired functionality:

     #show_textbox:not(:checked) + input[type=text] {display:none;}
    

    For other scenarios, you may think of appropriate CSS selectors.

    Here is a Fiddle to demonstrate this approach.

  54. 参考答案28
  55. if($("#checkkBoxId").is(':checked')){
      alert("Checked=true");
    }
    

    or

    if($("#checkkBoxId").attr('checked') == true){
      alert("checked=true");
    }
    
  56. 参考答案29
  57. I am using this:

     <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
     <input type="textbox" id="txtAge" />
    
     $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
    
  58. 参考答案30
  59. I'm sure it's not some revelation, but I didn't see it all in one example:

    Selector for all checked checkboxes(on the page):

    $('input[type=checkbox]:checked')