0

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.

Here is a jsFiddle

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.

1 Answer 1

1

Create your arrCB as an anonymous object, then loop over your checkboxes and assign their IDs in to arrCB:

$('#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);
});

Fiddle: http://jsfiddle.net/k20mug9y/2/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.