json to elements to javascript associative array to json
http://stackoverflow.com/questions/25395418/best-practice-for-updating-a-list-in-database-associated-with-checkboxes-in-a-ht
HTML
<p>http://stackoverflow.com/questions/25395418/best-practice-for-updating-a-list-in-database-associated-with-checkboxes-in-a-ht</p>
<div id="chkbox"></div>
<input type="button" id="create_cb" value="Create Checkboxes" />
<input type="button" id="mybutt" value="Add New Checkbox" />
<input type="button" id="display_all" value="Display JSON String" />
CSS
p {font-size:10px;color:blue;}
div{height:40px;width:300px;margin:20px;background:wheat;}
#mybutt,#display_all {display:none;}
JavaScript
var chk, json = '{"cb1":0,"cb2":0,"cb3":1,"cb4":0}';
$('#create_cb').click(function(){
var arrJson = JSON && JSON.parse(json) || $.parseJSON(json);
for(key in arrJson){
chk = (arrJson[key]==1)? 'checked="checked"' : '';
$('#chkbox').append(key +': <input id="'+key+'" type="checkbox" '+chk+' /> ');
}
$(this).hide();
$('#mybutt, #display_all').show();
});
$('#mybutt').click(function(){
var lbl = prompt('Label?');
$('#chkbox').append(lbl+ ': <input id="' +lbl+ '" type="checkbox" /> ');
});
$('#display_all').click(function(){
var arrCB = {};
$("#chkbox>input[type='checkbox']").each(function(){
var el = $(this);
var id = el.attr('id');
arrCB[id] = (this.checked ? 1 : 0)
});
var text = JSON.stringify(arrCB);
alert(text);
});