首页 文章

检查是否使用jQuery选中了复选框

提问于
浏览
983

如何检查复选框数组中的复选框是否使用复选框数组的ID进行检查?

我使用以下代码,但无论id如何,它始终返回已选中复选框的计数 .

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

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

20 回答

  • 5

    我知道OP想要jquery,但在我的情况下,纯JS是答案所以如果有人喜欢我在这里并且没有jquery或者不想使用它 - 这里是JS答案:

    document.getElementById("myCheck").checked
    

    如果选中ID为myCheck的输入,则返回true;如果未选中,则返回false .

    就那么简单 .

  • 4
    $('#checkbox').is(':checked');
    

    如果选中复选框,则上面的代码返回true,否则返回false .

  • 59

    以下所有方法都很有用:

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

    建议应该避免使用DOMelement或内联“this.checked”,而应该使用jQuery on方法事件监听器 .

  • 70

    只是在我的示例中说情况是一个对话框,然后在关闭对话框之前验证复选框 . 以上都没有,How to check whether a checkbox is checked in jQuery?jQuery if checkbox is checked似乎也不起作用 .

    到底

    <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');
    

    这样就可以调用类,然后调用ID . 而不仅仅是ID . 这可能是由于此页面上的嵌套DOM元素导致问题 . 解决方法在上面 .

  • 24

    根据jQuery documentation,有以下方法可以检查是否选中了复选框 . 让我们考虑一个复选框作为示例(使用所有示例检查工作jsfiddle

    <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.");
        }
    });
    

    检查工作jsfiddle

  • 10

    你可以使用这段代码,

    if($("#checkboxId").is(':checked')){
         // Code in the case checkbox is checked.
    } else {
         // Code in the case checkbox is NOT checked.
    }
    
  • 5

    要记住关于checked属性的最重要的概念是它与checked属性不对应 . 该属性实际上对应于defaultChecked属性,应仅用于设置复选框的初始值 . checked属性值不会随复选框的状态而改变,而checked属性则会改变 . 因此,确定是否选中复选框的跨浏览器兼容方式是使用该属性

    以下所有方法都是可行的

    elem.checked 
    
    $(elem).prop("checked") 
    
    $(elem).is(":checked")
    
  • 7

    像这样的东西可以帮助

    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 );
            }
        }
    }
    
  • -3
    $('#' + id).is(":checked")
    

    如果选中该复选框,则会得到 .

    对于具有相同名称的复选框数组,您可以通过以下方式获取已选中的复选框列表:

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

    然后循环遍历它们,看看你可以做什么检查:

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

    要查找已检查的数量,您可以执行以下操作:

    $boxes.length;
    
  • 4

    选中切换复选框

    $("#checkall").click(function(){
        $("input:checkbox").prop( 'checked',$(this).is(":checked") );
    })
    
  • 32

    ID必须在您的文档中是唯一的,这意味着您 shouldn't 执行此操作:

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

    相反,删除ID,然后按名称或包含元素选择它们:

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

    现在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;
    
  • 20

    用于检查复选框是否已选中的jQuery代码:

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

    或者:

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

    用于检查和设置复选框的简单演示 .

    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);
        }
    });
    
  • 87

    使用下面的代码

    <script>
    
    $(document).ready(function () {
      $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
    }
    
    function ShowMailSection() {
      if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
          $("[id$='SecEmail']").removeClass("Hide");
      }
    </script>
    
  • 600

    你可以试试这个:

    <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" />
    
  • 1754

    你可以这样做;

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

    甚至更简单;

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

    如果 checkbox 被选中,它将返回 true 否则 undefined

  • 0

    实际上,根据jsperf.com,DOM操作最快,然后$() . prop()后跟$() . is()!!

    以下是语法:

    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!!');
    

    我个人更喜欢 .prop() . 与 .is() 不同,它也可用于设置值 .

  • 254

    对于带有id的复选框

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

    你可以干脆做

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

    您将获得 truefalse 作为上述语法的返回值 . 您可以在if子句中将其用作普通布尔表达式 .

  • 27

    使用此代码,您可以选中是否在不同的复选框组或多个复选框中选中或不选中一个复选框 . 使用此功能,您无需删除ID或动态ID . 此代码使用相同的ID .

    参考Link

    <label class="control-label col-sm-4">Check Box 2</label>
        <input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1
    <input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2
    <label class="control-label col-sm-4">Check Box 3</label> <input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3
    <input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4
    <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>
  • 7

    您可以通过jquery使用以下任何建议的代码 .

    if ( elem.checked ) {};
    if ( $( elem ).prop( "checked" ) ) {};
    if ( $( elem ).is( ":checked" ) ) {};
    

相关问题