javascript 如何使用 Jquery 从复选框中收集值的 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14816337/
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-10-26 22:39:21  来源:igfitidea点击:

How to collect JSON object of values from checkboxes, using Jquery?

javascriptjqueryjson

提问by you-rick

I'm trying to create some kind of small contact table for users, where they can select when is more comfortable to contact them. I have 7 days and 3 conditions - Morning/Afternoon/Evening.

我正在尝试为用户创建某种小型联系表,他们可以在其中选择更方便的联系时间。我有 7 天和 3 个条件 - 早上/下午/晚上。

I'm trying to collect this kind of object, to send it to the server -

我正在尝试收集这种对象,将其发送到服务器 -

{"SUNDAY":["MORNING"],"MONDAY":["EVENING","MORNING"]}

I have the following HTML structure:

我有以下 HTML 结构:

<tr>
<td class="table-headline">Morning</td>
<td>                                
    <label class="label-check">
        <input id="morning1" name="morning" type="checkbox" value="SUNDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning2" name="morning" type="checkbox" value="MONDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning3" name="morning" type="checkbox" value="TUESDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning4" name="morning" type="checkbox" value="WEDNESDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning5" name="morning" type="checkbox" value="THURSDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning6" name="morning" type="checkbox" value="FRIDAY">
</label>   
</td>
<td>                                
    <label class="label-check">
        <input id="morning7" name="morning" type="checkbox" value="SATURDAY">
</label>   
</td>

I have three similar lines for each condition. It is not a problem, to detect, if checkbox checked or not, i don't know how to collect in JSON this data after checking.

对于每个条件,我都有三个类似的行。检测是否选中复选框不是问题,我不知道如何在检查后以 JSON 收集这些数据。

回答by nice ass

This should do it (assuming the checkboxes are wrapped in a form element):

这应该这样做(假设复选框包含在表单元素中):

var data = $('form').serializeArray(),
    obj = {};

for(var i = 0; i < data.length; i++){
   obj[data[i].name] = obj[data[i].name] || [];
   obj[data[i].name].push(data[i].value);
}    

// your JSON string
console.log(JSON.stringify(obj));

Edit:I see that you have the name and values reversed in your sample string. If this is intended and not a typo, simply swap namewith valueproperties in the code above.

编辑:我看到您的示例字符串中的名称和值颠倒了。如果这是故意的而不是拼写错误,只需namevalue上面代码中的属性交换即可。

回答by Qpirate

Just as an FYI i have created my input for this. its here

正如仅供参考,我为此创建了我的输入。它在这里

The JS code is as follows

JS代码如下

$('#btnsubmit').click(function () {

    var obj = [];
    obj.push({
        "MONDAY": GetDetails("MONDAY"),
        "TUESDAY": GetDetails("TUESDAY"),
        "WEDNESDAY": GetDetails("WEDNESDAY"),
        "THURSDAY": GetDetails("THURSDAY"),
        "FRIDAY": GetDetails("FRIDAY"),
        "SATURDAY": GetDetails("SATURDAY"),
        "SUNDAY": GetDetails("SUNDAY"),
    });
$('#output').text(JSON.stringify(obj));
});

function GetDetails(day) {
    var arr = new Array();
    $(':input[value="' + day + '"]').each(function () {
        if (this.checked) {
            arr.push($(this).attr('name'));
        }
    });
        return arr;
}

the Output is as follows

输出如下

[{
"MONDAY":["afternoon"],
"TUESDAY":[],
"WEDNESDAY":["morning","afternoon"],
"THURSDAY":[],
"FRIDAY":["morning","afternoon"],
"SATURDAY":[],
"SUNDAY":[]
}]

回答by Shanimal

$('input').on('click',function(){
  // selectors that are checked => $('input:checked').length
  console.log($('input:checked').length)
})