如何检查使用jQuery选中的多个复选框? [英] How to check multiple checkboxes checked using jquery?

查看:67
本文介绍了如何检查使用jQuery选中的多个复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手,这很有趣,但是我有一个小问题, 我正在使用这样的foreach循环从数据库中填充多个复选框,

i am new to the jquery, it is quite interesting, but i am having a little problem, i am populating multiple checkboxes from database using foreach loop like this,

<? foreach($cities as $city) { ?>
    <input type="checkbox" name="city[]" value="<?=$city->id?>" id="city[]" />
<? } ?>

我想限制用户选中至少一个复选框,我知道如何仅使用一个复选框,但是在jquery中与这种数组混淆,任何帮助将不胜感激! 提前非常感谢!

i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated! Many thanks in advance!

推荐答案

要查找选中了多少个复选框,可以使用类似以下内容的东西:

To find how many checkboxes are checked, you can use something like:

var checkedNum = $('input[name="city[]"]:checked').length;
if (!checkedNum) {
    // User didn't check any checkboxes
}

由于要为所有复选框(从PHP循环中)提供相同的name属性,因此可以使用选择器input[name="city[]"]定位并查找所有复选框.但是要找出已选中的具体数量,您可以添加:checked选择器.替代方法是使用$('input[name="city[]"]').filter(":checked").

Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').filter(":checked").

最后,如果checkedNum为0,则!checkedNum将仅通过,因为0为假.任何其他数字都是真实的,并且不满足条件!checkedNum.

Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.

参考:

  • jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
  • :checked selector: http://api.jquery.com/checked-selector/
  • jQuery .length property: http://api.jquery.com/length/

这篇关于如何检查使用jQuery选中的多个复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆