我正在尝试为用户创建某种小型联系人表,他们可以选择何时更方便联系他们。我有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这个数据,这不是问题。
答案 0 :(得分: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
属性进行交换。
答案 1 :(得分:1)
正如我所知,我为此创建了我的输入。它的here
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":[]
}]
答案 2 :(得分:0)
$('input').on('click',function(){
// selectors that are checked => $('input:checked').length
console.log($('input:checked').length)
})