简体   繁体   English

检查是否至少使用 jQuery 选中了一个复选框

[英]Check if at least one checkbox is checked using jQuery

I have five checkboxes.我有五个复选框。 Using jQuery, how do I check if at least one of them is checked?使用 jQuery,如何检查是否至少检查了其中之一?

<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">

is() can do this, and is arguably the only acceptable use of is(":checked") : is()可以做到这一点,并且可以说is(":checked")唯一可以接受的用法:

From the jQuery docs, http://api.jquery.com/is/ :从 jQuery 文档, http : //api.jquery.com/is/

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.根据选择器、元素或 jQuery 对象检查当前匹配的一组元素,如果这些元素中至少有一个与给定的参数匹配,则返回 true。

 alert($("input[name='service[]']").is(":checked"));

Example: http://jsfiddle.net/AndyE/bytVX/1/ (based on the fiddle by Brandon Gano )示例: http : //jsfiddle.net/AndyE/bytVX/1/ (基于Brandon Gano的小提琴)

Alternatively, and potentially faster, you can pass a function to is() :或者,可能更快,您可以将函数传递给is()

$("input[name='service[]']").is(function () {
    return this.checked;
});

Edit: The original solution in this answer is inefficient and should not be used.编辑:此答案中的原始解决方案效率低下,不应使用。 Please see the revised solution based on comments and examples from other answers to this question.请参阅基于对此问题的其他答案的评论和示例的修订解决方案。

The original (bad) solution follows:原始(坏)解决方案如下:

// DO NOT USE; SEE BELOW
$('button').click(function () {
  var atLeastOneIsChecked = false;
  $('input:checkbox').each(function () {
    if ($(this).is(':checked')) {
      atLeastOneIsChecked = true;
      // Stop .each from processing any more items
      return false;
    }
  });
  // Do something with atLeastOneIsChecked
});

The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one.在这个例子中 .each() 的使用是多余的,因为 .is() 可以直接在一组对象上使用,而不是手动迭代每个对象。 A more efficient solution follows:一个更有效的解决方案如下:

$('button').click(function () {
  var atLeastOneIsChecked = $('input:checkbox').is(':checked');
  // Do something with atLeastOneIsChecked
});

Note that one of the comments indicates a strong dislike for $(this).is(':checked') .请注意,其中一条评论表明非常不喜欢$(this).is(':checked') To clarify, there is nothing wrong with is(':checked') in cases where you are testing a set of objects.澄清is(':checked') ,在您测试一组对象的情况下, is(':checked')没有任何问题。 That said, calling is(':checked') on a single item is much less efficient than calling .checked on the same item.也就是说,在单个项目上调用is(':checked')比在同一项目上调用.checked效率低得多。 It also involves an unnecessary call to the $ function.它还涉及对 $ 函数的不必要调用。

This should do the trick:这应该可以解决问题:

function isOneChecked() {
    return ($('[name="service[]"]:checked').length > 0);
}

Another answer:另一个答案:

!!$("[type=checkbox]:checked").length

or要么

!!$("[name=service[]]:checked").length

It depends on what you want.这取决于你想要什么。

You should try like this....你应该像这样尝试......

var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");

checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));

}); });

you need to check if checkbox is checked or not.您需要检查复选框是否被选中。

$("#select_all").click(function(){
           var checkboxes = $("input[type='checkbox']");
           if(checkboxes.is(":checked"))
               alert("checked");
           else
               alert("select at least one;      

            });
var checkboxes = document.getElementsByName("service[]");
if ([].some.call(checkboxes, function () { return this.checked; })) {
  // code
}

What you want is simple, get all the elements with the name, then run some code if some of those elements are checked.您想要的很简单,获取所有具有名称的元素,然后在检查其中一些元素时运行一些代码。

No need for jQuery.不需要 jQuery。

You may need an ES5 shim for legacy browsers though不过,对于旧版浏览器,您可能需要 ES5 垫片

You can do the following way.您可以通过以下方式进行。 Initially set a variable, lets say checked as false .最初设置一个变量,假设checkedfalse Then set it to true if the following condition met.如果满足以下条件,则将其设置为true Use an if statement to check the variable.使用if语句检查变量。 Take note: Here submit is the id of the button, main is the id of the form.注意:这里submitid按钮, main是形式的ID。

 $("#submit").click(function() { var checked = false; if (jQuery('#main input[type=checkbox]:checked').length) { checked = true; } if (!checked) { //Do something } });

The square bracket [] is not necessary:方括号[]不是必需的:

var atLeastOneIsChecked = $("input[name='service']:checked").length > 0;

The same goes to your HTML, but better to have an id to uniquely identify each of the checkboxes:您的 HTML 也是如此,但最好有一个id来唯一标识每个复选框:

<input id="chk1" type="checkbox" name="service">
<br />
<input id="chk2" type="checkbox" name="service">
<br />
<input id="chk3" type="checkbox" name="service">
<br />
<input id="chk4" type="checkbox" name="service">
<br />
<input id="chk5" type="checkbox" name="service">
var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;

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

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