2

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

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

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

我有以下 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>

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

4

3 回答 3

4

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

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));

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

于 2013-02-11T16:37:28.883 回答
1

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

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;
}

输出如下

[{
"MONDAY":["afternoon"],
"TUESDAY":[],
"WEDNESDAY":["morning","afternoon"],
"THURSDAY":[],
"FRIDAY":["morning","afternoon"],
"SATURDAY":[],
"SUNDAY":[]
}]
于 2013-02-11T16:52:03.723 回答
0
$('input').on('click',function(){
  // selectors that are checked => $('input:checked').length
  console.log($('input:checked').length)
})
于 2013-02-11T16:31:18.257 回答