Reputation: 185
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.
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:
<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.
Upvotes: 2
Views: 11996
Reputation: 2078
Just as an FYI i have created my input for this. its here
The JS code is as follows
$('#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":[]
}]
Upvotes: 1
Reputation: 16709
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 name
with value
properties in the code above.
Upvotes: 4
Reputation: 11718
$('input').on('click',function(){
// selectors that are checked => $('input:checked').length
console.log($('input:checked').length)
})
Upvotes: 0