来自JSON Array的动态CheckBox [英] Dynamic CheckBoxes from JSON Array
问题描述
我是JavaScript / JQuery的新手,我不知道如何才能做到这一点。也许每个部分的一个小例子可以帮助。
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.
说我有< div id =checkboxes>< / div>
当页面加载时,我将进行一个将返回JSON数组的ajax调用。我知道该怎么做。
When the page loads, I will make an ajax call that will return JSON array. This I know how to do.
对象将是这样的:
[
{
name: "Item 1",
id: "27",
checked: "true"
}
...
]
我需要以某种方式接受JSON响应并在其中注入一些复选框div也将存储ID。复选框文本将是'name'。
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'.
然后,我需要知道如何在选中任何复选框时附加函数,我需要获取'id',因为我会在任何选中的更改时执行ajax调用。
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.
使用JQuery执行此类操作的任何示例都将非常有用。
Any examples of doing this sort of thing with JQuery would be very helpful.
谢谢
推荐答案
第1部分(创建方框):
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)
));
});
第2部分(动态提取ID):
Part 2 (dynamic fetching of ID):
$("#checkboxes").on('change', '[type=checkbox]', function () {
//this is now the checkbox; this.value is the id.
});
这篇关于来自JSON Array的动态CheckBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!