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

时间:2010-02-05 00:23:21

标签: javascript jquery checkbox

如何使用复选框数组的ID检查复选框数组中的复选框?

我正在使用以下代码,但无论id是什么,它都会返回已选中复选框的计数。

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

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

25 个答案:

答案 0 :(得分:1856)

$('#' + id).is(":checked")

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

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

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

然后循环浏览它们,看看你能做什么检查:

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

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

$boxes.length;

答案 1 :(得分:625)

您的文档中的ID必须是唯一的,这意味着不应执行此操作:

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

答案 2 :(得分:270)

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

如果选中复选框,则上述代码返回true,否则返回false。

答案 3 :(得分:103)

以下所有方法都很有用:

$('#checkbox').is(":checked")

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

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

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

答案 4 :(得分:85)

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

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

可替换地:

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

答案 5 :(得分:61)

  

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

以下所有方法都是可能的

elem.checked 

$(elem).prop("checked") 

$(elem).is(":checked") 

答案 6 :(得分:35)

您可以使用此代码

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

答案 7 :(得分:31)

这也是我经常使用的想法:

var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;

如果有问题,它将返回1;否则它将返回0。

答案 8 :(得分:27)

根据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" />

示例1 - 选中

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

示例2 - 使用jQuery,注意 - :选中

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

示例3 - 使用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

答案 9 :(得分:26)

你可以试试这个:

<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 :(得分:21)

您可以通过jquery使用以下任何推荐代码。

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

答案 11 :(得分:17)

我知道OP需要jquery,但就我而言,纯JS是答案,因此,如果像我这样的人在这里并且没有jquery或不想使用它-这是JS答案:

document.getElementById("myCheck").checked

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

就这么简单。

答案 12 :(得分:10)

你可以这样做;

<强> 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

答案 13 :(得分:7)

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

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

答案 14 :(得分:6)

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

最后

ThreadPool

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

答案 15 :(得分:5)

对于ID为

的复选框
<input id="id_input_checkbox13" type="checkbox"></input>

你可以简单地做

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

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

答案 16 :(得分:5)

这样的事可以帮助

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

答案 17 :(得分:4)

选中切换复选框

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

答案 18 :(得分:4)

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

以下是语法:

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()不同,它也可用于设置值。

答案 19 :(得分:4)

$(document).on('click','#checkBoxId',function(){
  var isChecked = $(this).is(':checked');
  console.log(isChecked);
});

上面的这段代码也适用于引导模式。 isChecked 是 true 或 flase ;

答案 20 :(得分:2)

您的问题尚不清楚:您想在输入中提供“复选框数组ID”,并在输出中获得true/false-这样,您将不知道选中了哪个复选框(如您的函数名所建议)。因此,下面是我的isCheckedById主体主张,它在输入复选框id和输出返回true/false(很简单,但您的ID不应该是关键字),

this[id].checked

function isCheckedById(id) {
  return this[id].checked;
}



// TEST

function check() {
  console.clear()
  console.log('1',isCheckedById("myCheckbox1"));
  console.log('2',isCheckedById("myCheckbox2"));
  console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>

答案 21 :(得分:2)

检查复选框的各种方法:

使用Prop方法:

<script>
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).prop("checked") == true){
                console.log("Checkbox is checked.");
            }
            else if($(this).prop("checked") == false){
                console.log("Checkbox is unchecked.");
            }
        });
    });
</script>

使用 :checkselector 方法:

<script>
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).is(":checked")){
                console.log("Checkbox is checked.");
            }
            else if($(this).is(":not(:checked)")){
                console.log("Checkbox is unchecked.");
            }
        });
    });
</script>

.attr 方法:

$('input[type=checkbox]').attr('checked');

您可以根据需要使用。

答案 22 :(得分:1)

自2019年中期以来,jQuery有时会在诸如VueJS,React等方面倒退。这是一个纯香草Javascript onload监听器选项:

<script>
  // Replace 'admincheckbox' both variable and ID with whatever suits.

  window.onload = function() {
    const admincheckbox = document.getElementById("admincheckbox");
    admincheckbox.addEventListener('click', function() {
      if(admincheckbox.checked){
        alert('Checked');
      } else {
        alert('Unchecked');
      }
    });
  }
</script>

答案 23 :(得分:0)

使用此代码,您可以选中是否在不同的复选框组或多个复选框中选中或不选中一个复选框。 使用此功能,您无需删除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<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>

答案 24 :(得分:-3)

使用下面的代码

<script>

$(document).ready(function () {
  $("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}

function ShowMailSection() {
  if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
      $("[id$='SecEmail']").removeClass("Hide");
  }
</script>
相关问题