最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic CheckBoxes from JSON Array - Stack Overflow

programmeradmin0浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论