jQuery 循环检查复选框并计算每个选中或未选中的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1965075/
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
Loop through checkboxes and count each one checked or unchecked
提问by Richard M
I've run into a bit of an issue. Here's a brief explanation.
我遇到了一点问题。这是一个简短的解释。
I have 12 check boxes on a standard form. What I need to do is loop through each of them and learn which ones are checked and which ones are unchecked.
我在标准表单上有 12 个复选框。我需要做的是遍历它们中的每一个,并了解哪些已选中,哪些未选中。
Using this, I can then build a string which I then enter into a database field. Here is an example.
使用它,我可以构建一个字符串,然后将其输入到数据库字段中。这是一个例子。
(Check1 - checked)
(Check2 - not checked)
(Check3 - checked)
(Check1 - 选中)
(Check2 - 未选中)
(Check3 - 选中)
1,0,1
1,0,1
So far, I've got this bit of code.
到目前为止,我已经得到了这段代码。
$('input[type=checkbox]').each(function () {
if (this.checked) {
console.log($(this).val());
}
});
It works perfectly except that it only brings back the checked ones, not all.
它工作得很好,只是它只带回检查过的,而不是全部。
Sorry for the newb question. I'm kinda new to jquery.
对不起,新问题。我对 jquery 有点陌生。
回答by Ed Schembor
To build a result string exactly in the format you show, you can use this:
要完全按照您显示的格式构建结果字符串,您可以使用以下命令:
var sList = "";
$('input[type=checkbox]').each(function () {
sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
});
console.log (sList);
However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.
但是,我同意@SLaks,我认为您应该重新考虑将其存储在数据库中的结构。
EDIT: Sorry, I mis-read the output format you were looking for. Here is an update:
编辑:对不起,我误读了您正在寻找的输出格式。这是一个更新:
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);
回答by Sampson
Using Selectors
使用选择器
You can get all checked checkboxes like this:
您可以像这样获得所有选中的复选框:
var boxes = $(":checkbox:checked");
And all non-checked like this:
并且所有未检查如下:
var nboxes = $(":checkbox:not(:checked)");
You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array()
request to know whether or not any particular box should be checked at a later date.
您可以只循环浏览这些集合中的任何一个,并存储这些名称。如果没有任何东西,你就知道它要么被检查,要么没有被检查。在 PHP 中,如果您有一个被选中的名称数组,您可以简单地发出in_array()
请求以了解以后是否应该选中任何特定的框。
Serialize
连载
jQuery also has a serialize methodthat will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:
jQuery 还有一个serialize 方法可以维护表单控件的状态。例如,jQuery 网站上提供的示例如下:
single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2
This will enable you to keep the information for which elements were checked as well.
这将使您能够保留已检查元素的信息。
回答by SLaks
You can loop through all of the checkboxes by writing $(':checkbox').each(...)
.
您可以通过编写遍历所有复选框$(':checkbox').each(...)
。
If I understand your question correctly, you're looking for the following code:
如果我正确理解您的问题,您正在寻找以下代码:
var str = "";
$(':checkbox').each(function() {
str += this.checked ? "1," : "0,";
});
str = str.substr(0, str.length - 1); //Remove the trailing comma
This code will loop through all of the checkboxes and add either 1,
or 0,
to a string.
通过所有的复选框,并添加该代码将循环要么1,
或者0,
为一个字符串。
回答by Nathon
I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.
我认为没有足够的时间关注原始帖子中提出的架构注意事项。所以,这里是任何新手都需要考虑的事情。
Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.
假设您继续构建此解决方案。您所有的微不足道的价值都被合并成一个单一的价值并存储在数据库中。您确实在数据库中节省了 [一点] 空间和一些时间编码。
Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.
现在让我们考虑一下,您必须执行在当前复选框 3 和 4 之间添加新复选框的频繁且简单的任务。您的开发经理、客户,无论期望这是一个简单的更改。
So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.
因此,您将复选框添加到 UI(简单部分)。无论有多少复选框,您的循环代码都已经连接了这些值。您还认为您的数据库字段只是一个 varchar 或其他字符串类型,所以它也应该没问题。
What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.
当客户或您尝试查看更改前的数据时会发生什么?你基本上是从左到右序列化。但是,现在 3 之后的值都相差 1 个字符。您将如何处理所有现有数据?您是否要编写一个应用程序,将其全部从数据库中取出,对其进行处理以添加新问题位置的默认值,然后将其全部存储回数据库中?当您在一周或一个月内有几个新值时会发生什么?如果您移动位置并且 jQuery 以不同的顺序处理它们会怎样?您的所有数据都已被处理,必须再次重新处理以重新排列。
The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.
不提供紧密的键值关系的整个概念是 ludacris,最终会让您迟早陷入麻烦。对于那些考虑这个的人,请不要。架构更改的其他建议很好。使用子表、主表中的更多字段、问答表等。当数据结构可能发生变化时,不要存储未标记的数据。
回答by Thulasiram
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
});
$("input:checked")
$("input:unchecked")