循环通过复选框,并计数每个选中或取消选中 [英] Loop through checkboxes and count each one checked or unchecked
问题描述
我遇到了一个问题。这里有一个简短的解释。
I've run into a bit of an issue. Here's a brief explanation.
我有一个标准窗体上的12个复选框。我需要做的是循环遍历它们,并了解哪些被检查和哪些被取消检查。
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.
使用它,我可以构建一个字符串,然后输入到数据库字段。这里是一个例子。
Using this, I can then build a string which I then enter into a database field. Here is an example.
(选中1 - 已选中)
(选中2 - 未选中)
(选中3 - 已选中)
(Check1 - checked)
(Check2 - not checked)
(Check3 - checked)
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.
对不起,newb的问题。
Sorry for the newb question. I'm kinda new to jquery.
推荐答案
要以您显示的格式完全建立结果字符串,可以使用:
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);
但是,我同意@SLaks,我认为你应该重新考虑你的结构将会将其存储在您的数据库中。
However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.
编辑:对不起,我错读了您正在查找的输出格式。这是一个更新:
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);
这篇关于循环通过复选框,并计数每个选中或取消选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!