php 如何检查使用jquery检查的多个复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16161741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:37:47  来源:igfitidea点击:

How to check multiple checkboxes checked using jquery?

phpjavascriptjquery

提问by Irfan Ahmed

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,

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

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

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!

我想限制用户检查至少一个复选框,我知道如何只用一个复选框来做到这一点,但对 jquery 中的这种数组感到困惑,任何帮助将不胜感激!提前谢谢了!

回答by Ian

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
}

Since you're providing the same nameattribute 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 :checkedselector. An alternative to this is using $('input[name="city[]"]').filter(":checked").

由于您name为所有复选框(来自 PHP 循环)提供了相同的属性,因此您可以使用选择器input[name="city[]"]来定位并找到它们。但是要找出具体检查了多少,您可以添加:checked选择器。另一种方法是使用$('input[name="city[]"]').filter(":checked").

Finally, !checkedNumwill onlypass if checkedNumis 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.

最后,只有在0!checkedNum才会通过checkedNum,因为 0 是假的。任何其他数字都是真实的,并且不满足条件!checkedNum



References:

参考:

回答by Robbert

If you want at least one checkbox checked, you can use this

如果你想至少选中一个复选框,你可以使用这个

var somethingChecked = false;
$("input[type=checkbox]").each(function() {
  if(this).is(':checked')) {
    somethingChecked = true;
  }
});
if(!somethingChecked) {
  alert("You haven't checked anything yet");
}

What this does is initialize a variable to false. Then the script loops through all inputs of type checkbox. If the item is checked, set the variable to true. Finally, check if the variable is still false. If it is, then show an error.

这样做是将一个变量初始化为 false。然后脚本循环遍历所有复选框类型的输入。如果该项目被选中,则将该变量设置为 true。最后,检查变量是否仍然为假。如果是,则显示错误。

回答by Mark Garcia

Assuming you have #my_formas the ID of your form, you could do

假设你有#my_form你的表单的 ID,你可以做

$("#my_form input[type=checkbox]:checked"). // ... do something

to select and do something with the checked checkboxes. You can also do

选择并使用选中的复选框执行某些操作。你也可以这样做

$("#my_form input[type=checkbox]").each(function(idx, elem) {
   var is_checked = $(this).prop("checked");
   // Do something with is_checked
});

to iterate through all the checkboxes and check whether they are checked or not.

遍历所有复选框并检查它们是否被选中。

回答by kiranvj

First of all idof the checkboxes should be unique.

首先,id复选框应该是唯一的。

Do like this

这样做

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

Now in jQuery check like this to get all the checkboxes thats checked.

现在在 jQuery 中像这样检查以获取所有选中的复选框。

var checkCount = $("input[name='city[]']:checked").length;

if(checkCount == 0)
{
   alert("Atleast one checkbox should be checked.");
}

回答by sandeep kumar

This code work well for me,here i convert array to string with ~

这段代码对我来说效果很好,在这里我将数组转换为字符串~

    <input type="checkbox" value="created" name="today_check"><strong>Created</strong>
    <input type="checkbox" value="modified" name="today_check><strong>Modified</strong>
 <a class="get_tody_btn">Submit</a>

<script type="text/javascript">
    $('.get_tody_btn').click(function(){
        var vals = "";
        $.each($("input[name='today_check']:checked"), function(){  
            vals += "~"+$(this).val();  
        });
        if (vals){
            vals = vals.substring(1);
        }else{
            alert('Please choose atleast one value.');
        }


    });
</script>