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.

推荐答案

要完全按照显示的格式生成结果字符串,可以使用以下方法:

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:对不起,我误读了您要查找的输出格式.以下是最新消息:

var sList = "";
$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? "1" : "0");
    sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);

Jquery相关问答推荐

通过 jQuery 提取 application/json 数据

如果您的 Select 器对象无效,为什么 jQuery 不会炸弹?

禁用提交按钮,直到所有字段都有值

foreach for JSON 数组,语法

$.each() 与 for() 循环 - 和性能

如何使用 AJAX 和 jQuery 发布 django 表单

用按钮切换显示/隐藏div?

Google Maps API v3 infowindow 关闭事件/回调?

如何在 Slick 轮播项目之间添加空格

jQuery中追加的相反

jQuery getJSON 将结果保存到变量中

在jQuery中将逗号添加到数字

您如何处理 jQuery 中的表单更改?

为什么不推荐$().ready(handler)?

在ajax请求中检测重定向?

如何使用 JQuery 获取 GET 和 POST 变量?

用于发布和获取的 Ajax 教程

默认情况下如何将tinymce粘贴为纯文本

bootstrap 日期和时间 Select 器

如何让 jQuery 等到效果完成?