简体   繁体   English

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

[英]Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?如何使用复选框数组的 id 检查复选框数组中的复选框是否被选中?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.我正在使用以下代码,但它总是返回选中复选框的计数,而不管 id。

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

    if (checked == 0) {
        return false;
    } else {
        return true;
    }
}
$('#' + 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;

IDs must be unique in your document, meaning that you shouldn't do this: ID 在您的文档中必须是唯一的,这意味着您不应该这样做:

<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:相反,删除 ID,然后按名称或包含元素选择它们:

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

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

And now the jQuery:现在是 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;
$('#checkbox').is(':checked'); 

如果复选框被选中,上面的代码返回真,否则返回假。

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.建议应避免使用 DOMelement 或内联“this.checked”,而应使用 jQuery on 方法作为事件侦听器。

jQuery code to check whether the checkbox is checked or not:检查复选框是否被选中的jQuery代码:

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

Alternatively:或者:

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

The most important concept to remember about the checked attribute is that it does not correspond to the checked property.关于checked 属性要记住的最重要的概念是它不对应于checked 属性。 The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox.该属性实际上对应于 defaultChecked 属性,应该仅用于设置复选框的初始值。 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") 

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.
}

This is also an idea I use frequently:这也是我经常使用的一个想法:

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

If cheked, it'll return 1;如果检查,它将返回 1; otherwise it'll return 0.否则它会返回0。

As per the jQuery documentation there are following ways to check if a checkbox is checked or not.根据 jQuery文档,有以下方法可以检查复选框是否被选中。 Lets consider a checkbox for example (Check Working jsfiddle with all examples)例如,让我们考虑一个复选框(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示例 1 - 选中

$("#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示例 2 - 使用 jQuery,注意 - :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示例 3 - 使用 jQuery 道具

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检查工作jsfiddle

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

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:我知道 OP 想要 jquery,但在我的情况下,纯 JS 是答案,所以如果像我这样的人在这里并且没有 jquery 或不想使用它 - 这是 JS 答案:

document.getElementById("myCheck").checked

It returns true if the input with ID myCheck is checked and false if it is not checked.如果检查了 ID 为 myCheck 的输入,则返回 true,如果未检查,则返回 false。

Simple as that.就那么简单。

You can use any of the following recommended codes by jquery.您可以使用 jquery 推荐的以下任何代码。

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

You can do it simply like;你可以简单地这样做;

Working Fiddle工作小提琴

HTML HTML

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

jQuery 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如果checkbox被选中,它将返回true否则undefined

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

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?以上都不是以及如何检查是否在 jQuery 中选中了复选框? and jQuery if checkbox is checked did not appear to work either. 如果复选框被选中jQuery似乎也不起作用。

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.这很有效,所以先调用类,然后调用 ID。 rather than just the ID.而不仅仅是ID。 It may be due to the nested DOM elements on this page causing the issue.可能是由于此页面上的嵌套 DOM 元素导致了问题。 The workaround was above.解决方法如上。

For checkbox with an id对于带有 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.您将得到truefalse作为上述语法的返回值。 You can use it in if clause as normal boolean expression.您可以在 if 子句中将其用作普通布尔表达式。

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

Actually, according to jsperf.com , The DOM operations are fastest, then $().prop() followed by $().is()!!实际上,根据jsperf.com ,DOM 操作最快,然后是 $().prop() 然后是 $().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() .我个人更喜欢.prop() Unlike .is() , It can also be used to set the value..is()不同,它还可以用于设置值。

Toggle checkbox checked切换复选框已选中

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

This code above works also on bootstrap modal.上面的这段代码也适用于引导模式。 isChecked is true or flase ; isChecked 为 true 或 flase ;

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.使用此功能,您无需删除 ID 或动态 ID。 This code work with the same IDs.此代码使用相同的 ID。

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>

Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:由于是 2019 年年中,jQuery 有时会落后于 VueJS、React 等。这是一个纯粹的 vanilla 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>

Your question is not clear: you want to give "checkbox array id" at input and get true/false at output - in this way you will not know which checkbox was checked (as your function name suggest).您的问题不清楚:您想在输入时提供“复选框数组 id”并在输出时获得true/false - 这样您将不知道选中了哪个复选框(正如您的函数名称所暗示的那样)。 So below there is my proposition of body of your isCheckedById which on input take checkbox id and on output return true/false (it's very simple but your ID should not be keyword),所以下面是我对你的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>

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?如何使用复选框数组的 id 检查复选框数组中的复选框是否被选中?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.我正在使用以下代码,但它始终返回选中复选框的计数,而不管 id。

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

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

Try this...尝试这个...

$(function(){
  $('body').on('click','.checkbox',function(e){
    
    if($(this).is(':checked')){
      console.log('Checked')
    } else {
      console.log('Unchecked')
    }
  })
})

You can try either any of the ways preferred, as in jQuery or JavaScript .您可以尝试任何首选方式,如jQueryJavaScript

Get the value as below and assign to the variable then you if-else statements as per your requirement.获取如下值并分配给变量,然后根据您的要求使用if-else语句。

var getVal=$('#checkbox_id').is(":checked"); // jQuery

var getVal=document.getElementById("checkbox_id").checked //JavaScript

if (getVal==true) {
 // perform task
} else {
 // perform task 
}

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM