循环检查复选框并计算每个选中或未选中的复选框 [英] Loop through checkboxes and count each one checked or unchecked

查看:38
本文介绍了循环检查复选框并计算每个选中或未选中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

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)

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.

解决方案

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.

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屋!

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