简体   繁体   中英

populate multiple select boxes with single json string

I have string of data coming to the page via ajax. in the following format

[{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}]

I'd like to populate two select boxes with the data.

I've tried different variations of the following pseudo code:

for each item in the json string
if obj == servername
   add to selectbox Server
if obj == location
   add to selectbox Location

Any ideas would be greatly appreciated. Thanks.

var stuff = [{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}];

var elems = {
    "servername": jQuery('#select-server'),
    "location": jQuery('#select-location')
};

stuff.forEach(function(item){
    for(var selectName in elems){
        if(typeof item[selectName] != 'undefined'){
            var val = item[selectName];
            elems[selectName].append(jQuery('<option/>').val(val).html(val));
        }
    }
});

Not that forEach is not available on older browsers. The code above is just a sample for you to work with.

There are several ways to do this and depending on how your code might evolve in the future, some solutions might be slightly better than others or more flexible, but since I do not have such knowledge, here's an example on how you could do it in vanilla JS.

JSFIDDLE

var data = [
        {"servername":"svrA"},
        {"servername":"svrB"},
        {"servername":"svrC"},
        {"location":"locA"},
        {"location":"locB"},
        {"location":"locC"}
    ],
    selects = {
        servername: document.getElementById('servername'),
        location: document.getElementById('location')
    }, 
    i = 0,
    len = data.length,
    item, prop, val;

for (; i < len; i++) {
    prop = 'servername' in (item = data[i])? 'servername' : 'location';
    val = item[prop];
    selects[prop].add(new Option(val, val), null);
}

If you plan having the same kind of data structure for multiple select boxes, instead of hardcoding the selects object that references the select elements, you could also have pulled the select id dynamically using for in and also resolve the select reference using a generic approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM