weixin_41568196
撒拉嘿哟木头
采纳率40%
2010-02-05 00:23

用 jQuery 检查复选框是否被选中

已采纳

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

function isCheckedById(id) {
  alert(id);
  var checked = $("input[@id=" + id + "]:checked").length;
  alert(checked);

  if (checked == 0) {
    return false;
  } else {
    return true;
  }
}

转载于:https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

20条回答

  • weixin_41568127 ?yb? 11年前

    IDs must be unique in your document, meaning that you shouldn't do this:

    <input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
    <input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
    

    Instead, drop the ID, and then select them by name, or by a containing element:

    <fieldset id="checkArray">
        <input type="checkbox" name="chk[]" value="Apples" />
    
        <input type="checkbox" name="chk[]" value="Bananas" />
    </fieldset>
    

    And now the jQuery:

    var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
    //there should be no space between identifier and selector
    
    // or, without the container:
    
    var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
    
    点赞 23 评论 复制链接分享
  • csdnceshi54 hurriedly% 11年前
    $('#' + id).is(":checked")
    

    That gets if the checkbox is checked.

    For an array of checkboxes with the same name you can get the list of checked ones by:

    var $boxes = $('input[name=thename]:checked');
    

    Then to loop through them and see what's checked you can do:

    $boxes.each(function(){
        // Do stuff here with this
    });
    

    To find how many are checked you can do:

    $boxes.length;
    
    点赞 25 评论 复制链接分享
  • csdnceshi70 笑故挽风 9年前
    $('#checkbox').is(':checked'); 
    

    The above code returns true if the checkbox is checked or false if not.

    点赞 22 评论 复制链接分享
  • csdnceshi74 7*4 9年前

    You can try this:

    <script>
    function checkAllCheckBox(value)
    {
       if($('#select_all_').is(':checked')){
       $(".check_").attr ( "checked" ,"checked" );
        }
        else
        {
            $(".check_").removeAttr('checked');
        }
    
     }
    
    </script>
    <input type="checkbox" name="chkbox" id="select_all_" value="1" />
    
    
    <input type="checkbox" name="chkbox" class="check_" value="Apples" />
    <input type="checkbox" name="chkbox" class="check_" value="Bananas" />
    <input type="checkbox" name="chkbox" class="check_" value="Apples" />
    <input type="checkbox" name="chkbox" class="check_" value="Bananas" />
    
    点赞 10 评论 复制链接分享
  • csdnceshi67 bug^君 7年前

    You can do it simply like;

    Working Fiddle

    HTML

    <input id="checkbox" type="checkbox" />
    

    jQuery

    $(document).ready(function () {
        var ckbox = $('#checkbox');
    
        $('input').on('click',function () {
            if (ckbox.is(':checked')) {
                alert('You have Checked it');
            } else {
                alert('You Un-Checked it');
            }
        });
    });
    

    or even simpler;

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

    If the checkbox is checked it will return true otherwise undefined

    点赞 9 评论 复制链接分享
  • weixin_41568134 MAO-EYE 5年前

    Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.

    In the end

    <input class="cb" id="rd" type="checkbox">
    <input class="cb" id="fd" type="checkbox">
    
    var fd=$('.cb#fd').is(':checked');
    var rd= $('.cb#rd').is(':checked');
    

    This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.

    点赞 8 评论 复制链接分享
  • csdnceshi69 YaoRaoLov 5年前

    All following methods are useful:

    $('#checkbox').is(":checked")
    
    $('#checkbox').prop('checked')
    
    $('#checkbox')[0].checked
    
    $('#checkbox').get(0).checked
    

    It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.

    点赞 7 评论 复制链接分享
  • csdnceshi74 7*4 6年前

    You can use any of the following recommended codes by jquery.

    if ( elem.checked ) {};
    if ( $( elem ).prop( "checked" ) ) {};
    if ( $( elem ).is( ":checked" ) ) {};
    
    点赞 7 评论 复制链接分享
  • csdnceshi55 ~Onlooker 7年前

    For checkbox with an id

    <input id="id_input_checkbox13" type="checkbox"></input>
    

    you can simply do

    $("#id_input_checkbox13").prop('checked')
    

    you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.

    点赞 7 评论 复制链接分享
  • csdnceshi71 Memor.の 7年前

    Toggle checkbox checked

    $("#checkall").click(function(){
        $("input:checkbox").prop( 'checked',$(this).is(":checked") );
    })
    
    点赞 5 评论 复制链接分享
  • csdnceshi51 旧行李 5年前

    jQuery code to check whether the checkbox is checked or not:

    if($('input[name="checkBoxName"]').is(':checked'))
    {
      // checked
    }else
    {
     // unchecked
    }
    

    Alternatively:

    if($('input[name="checkBoxName"]:checked'))
    {
        // checked
    }else{
      // unchecked
    }
    
    点赞 4 评论 复制链接分享
  • csdnceshi62 csdnceshi62 6年前

    You can use this code,

    if($("#checkboxId").is(':checked')){
         // Code in the case checkbox is checked.
    } else {
         // Code in the case checkbox is NOT checked.
    }
    
    点赞 4 评论 复制链接分享
  • csdnceshi77 狐狸.fox 8年前

    The most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property

    All below methods are possible

    elem.checked 
    
    $(elem).prop("checked") 
    
    $(elem).is(":checked") 
    
    点赞 3 评论 复制链接分享
  • csdnceshi65 larry*wei 7年前

    Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

    Here are the syntaxes :

    var checkbox = $('#'+id);
    /* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
    
    /* The DOM way - The fastest */
    if(checkbox[0].checked == true)
       alert('Checkbox is checked!!');
    
    /* Using jQuery .prop() - The second fastest */
    if(checkbox.prop('checked') == true)
       alert('Checkbox is checked!!');
    
    /* Using jQuery .is() - The slowest in the lot */
    if(checkbox.is(':checked') == true)
       alert('Checkbox is checked!!');
    

    I personally prefer .prop(). Unlike .is(), It can also be used to set the value.

    点赞 2 评论 复制链接分享
  • csdnceshi56 lrony* 7年前

    As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)

    <input type="checkbox" name="mycheckbox" id="mycheckbox" />
    <br><br>
    <input type="button" id="test-with-checked" value="Test with checked" />
    <input type="button" id="test-with-is" value="Test with is" />
    <input type="button" id="test-with-prop" value="Test with prop" />
    

    Example 1 - With checked

    $("#test-with-checked").on("click", function(){
        if(mycheckbox.checked) {
            alert("Checkbox is checked.");
        } else {
            alert("Checkbox is unchecked.");
        }
    }); 
    

    Example 2 - With jQuery is, NOTE - :checked

    var check;
    $("#test-with-is").on("click", function(){
        check = $("#mycheckbox").is(":checked");
        if(check) {
            alert("Checkbox is checked.");
        } else {
            alert("Checkbox is unchecked.");
        }
    }); 
    

    Example 3 - With jQuery prop

    var check;
    $("#test-with-prop").on("click", function(){
        check = $("#mycheckbox").prop("checked");
        if(check) {
             alert("Checkbox is checked.");
        } else {
            alert("Checkbox is unchecked.");
        }
    }); 
    

    Check Working jsfiddle

    点赞 2 评论 复制链接分享
  • csdnceshi67 bug^君 3年前

    I know the OP want jquery but in my case pure JS was the answer so if anyone like me is here and do not have jquery or do not want to use it - here is the JS answer:

    document.getElementById("myCheck").checked
    

    It returns true if the input with ID myCheck is checked and false if it is not checked.

    Simple as that.

    点赞 2 评论 复制链接分享
  • csdnceshi79 python小菜 8年前

    Something like this can help

    togglecheckBoxs =  function( objCheckBox ) {
    
        var boolAllChecked = true;
    
        if( false == objCheckBox.checked ) {
            $('#checkAll').prop( 'checked',false );
        } else {
            $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
                if( false == chkbox.checked ) {
                    $('#checkAll').prop( 'checked',false );
                    boolAllChecked = false;
                }
            });
    
            if( true == boolAllChecked ) {
                $('#checkAll').prop( 'checked',true );
            }
        }
    }
    
    点赞 2 评论 复制链接分享
  • csdnceshi72 谁还没个明天 8年前

    Simple Demo for checking and setting a check box.

    jsfiddle!

    $('.attr-value-name').click(function() {
        if($(this).parent().find('input[type="checkbox"]').is(':checked'))
        {
            $(this).parent().find('input[type="checkbox"]').prop('checked', false);
        }
        else
        {
            $(this).parent().find('input[type="checkbox"]').prop('checked', true);
        }
    });
    
    点赞 1 评论 复制链接分享
  • csdnceshi79 python小菜 6年前

    use code below

    <script>
    
    $(document).ready(function () {
      $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
    }
    
    function ShowMailSection() {
      if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
          $("[id$='SecEmail']").removeClass("Hide");
      }
    </script>
    
    点赞 评论 复制链接分享
  • weixin_41568127 ?yb? 3年前

    Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes. Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.

    Reference Link

    <label class="control-label col-sm-4">Check Box 2</label>
        <input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
        <input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />
    
    <label class="control-label col-sm-4">Check Box 3</label>
        <input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
        <input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />
    
    <script>
    function checkFormData() {
        if (!$('input[name=checkbox2]:checked').length > 0) {
            document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
            return false;
        }
        if (!$('input[name=checkbox3]:checked').length > 0) {
            document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
            return false;
        }
        alert("Success");
        return true;
    }
    </script>
    
    点赞 评论 复制链接分享