I need to save/retrieve a series of checkboxes/values from webpage to PHP to MySQL, and back again.
In MySQL, they will be stored as a JSON string, like this: {"cb1":0,"cb2":0,"cb3":1,"cb4":0}
Everything is working except (1) reading the checkboxes+vals into an array, and (2) converting it back into JSON string as shown above.
It is the Display JSON List (#display_all)
button that needs rescuing.
Example HTML:
<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 list" />
Example JS:
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();
$('#display_all').show();
});
$('#display_all').click(function(){
var arrCB = $("#chkbox>input[type='checkbox']").map(function(){return this.value;});
var text = JSON.stringify(arrCB);
alert(text);
});
I have reviewed the following SO posts but cannot work out how to use these solutions in my case.
How can I send checkboxes data into JSON array?
JQuery: Turn array input values into a string optimization
Edit
I understand from this and this that the term "associative array" is incorrect. I am really creating an object with multiple properties. However, the term used best conveys the desired stringified result.