Dynamic CheckBoxes from JSON Array

I am new to JavaScript / jQuery and am not sure how to do this. Maybe a small example of each piece may help.

Let's say I have <div id="checkboxes"></div>

When the page loads, I will make an ajax call that will return a JSON array. This I know how to do it.

Objects will be like this:

 [ { name: "Item 1", id: "27", checked: "true" } ... ] 

I need to somehow take a JSON response and enter some checkboxes into this div, which will also keep the identifier. The text of the flag will indicate "name".

Then I need to know how to attach the function when any of these flags are checked, I will need to get an "id" at this point, because I will make an ajax call when any changes are noted.

Any examples of such actions with jQuery will be very helpful.

thanks

+4
source share
1 answer

Part 1 (creating boxes):

 $.each(json, function () { $("#checkboxes").append($("<label>").text(this.name).prepend( $("<input>").attr('type', 'checkbox').val(this.id) .prop('checked', this.checked) )); }); 

Part 2 (dynamic selection of identifier):

 $("#checkboxes").on('change', '[type=checkbox]', function () { //this is now the checkbox; this.value is the id. }); 

http://jsfiddle.net/g2zaR/

+5
source

All Articles