admin管理员组

文章数量:1335096

I am new to JavaScript / JQuery and I am not sure how I could do this. Maybe a small example of each part could help.

Say I have <div id="checkboxes"></div>

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

The objects will be like so:

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

I need to somehow take that JSON response and inject in some checkboxes into that div that will also store the ID. The checkbox text would be 'name'.

Then, I need to know how to attach a function for when any of these checkboxes are checked, I will need to get the 'id' at that point because I will do an ajax call when any checked changes.

Any examples of doing this sort of thing with JQuery would be very helpful.

Thanks

I am new to JavaScript / JQuery and I am not sure how I could do this. Maybe a small example of each part could help.

Say I have <div id="checkboxes"></div>

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

The objects will be like so:

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

I need to somehow take that JSON response and inject in some checkboxes into that div that will also store the ID. The checkbox text would be 'name'.

Then, I need to know how to attach a function for when any of these checkboxes are checked, I will need to get the 'id' at that point because I will do an ajax call when any checked changes.

Any examples of doing this sort of thing with JQuery would be very helpful.

Thanks

Share Improve this question asked Mar 5, 2013 at 17:21 jmasterxjmasterx 54.2k99 gold badges327 silver badges574 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Part 1 (creating the 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 fetching of ID):

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

http://jsfiddle/g2zaR/

本文标签: javascriptDynamic CheckBoxes from JSON ArrayStack Overflow