如何用JSON数据填充复选框

How to populate checkbox with JSON data

本文关键字:填充 复选框 数据 JSON 何用      更新时间:2023-09-26

我有一个网页,它从服务器接收以下JSON

{"d":[
    {"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS    "}
]}

根据该数据中的数组d,我需要创建复选框,每个复选框对应于数组的一个元素,由每个元素的operators属性定义。我需要这些复选框在收到数据后使用JavaScript/jQuery动态生成。如何做到这一点?

这就是您想要的吗?

var input=//get input json
var data=input.d;
for(var x in data){
    var type=data[x].__type;
    var ops=data[x].operators;
    var id="checkbox-"+ops+Math.floor(Math.random()*100000);
    $("<div><label></label><input/></div>")
        .children().eq(1)
            .attr({
                "type":"checkbox",
                "name":"insert here", 
                "data-type":type, 
                "data-operators":ops,
                "id":id,
                "class": "your checkbox class here"
             })
             .click(function(){ /////////////////////////// updated here
                 if($(this).prop("checked")){
                     // do action for checked event
                 } else {
                     // do action for unchecked event
                 }
             })
        .parent()
        .children().eq(0)
             .attr("for", id)
             .text("whatever label you want")
        .parent()
        .appendTo($("container you want to put them in"));
}

您应该循环JSON结果,创建checkbox元素并将其添加到div中。使用jquery .each()循环JSON。试试这个:

   var json = {"d":[
    {"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
    {"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS    "}
]};
    $(document).ready(function() {
        var $grouplist = $('#checkboxes');
        $.each(json.d, function() {
            $('<label>'+this.operators+': </label><input type=checkbox 
              value='+this.operators+'/>').appendTo($grouplist);
        });
    });

DEMO