Rudolf Lamprecht
Rudolf Lamprecht

Reputation: 1070

Bind JSON Array to select

I am trying to bind a JSON array, which is the result of an Ajax call, to a <select/> element.

A sample of the JSON structure is seen below:

[{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}]

What I need to achieve is to extract the JD_No value and JD_Name value of each element and bind them to a html <select/>

I must also state that the JSON Key is dynamic, so referencing a specific Key Name will not be possible.

Any help please?

Upvotes: 1

Views: 25867

Answers (6)

Dart
Dart

Reputation: 787

Try this http://jsfiddle.net/SPMJz/

HTML

<select id="select"></select>

Javascript

window.onload = function(){
    var data = [
        {"JD_No":1,"JD_Name":"Network Administrator"},
        {"JD_No":2,"JD_Name":"System Administrator"}
    ];

    populateSelect(data, 'number', 'string');
}

function populateSelect(data, idType, nameType){
    if(!data || !data[0]){
        return;
    }

    var select  = document.getElementById('select');
    var keys    = Object.keys(data[0]);
    var idKey   = typeof(parseInt(keys[0])) == idType   ? keys[0] : keys[1];
    var nameKey = typeof(parseInt(keys[0])) == nameType ? keys[0] : keys[1];

    for(var i = 0; i < data.length; i++){
        var option = document.createElement('option');
        option.value = data[i][idKey];
        option.label = data[i][nameKey];
        select.appendChild(option);
    }
}

Upvotes: 2

c.P.u1
c.P.u1

Reputation: 17094

Based on the assumption that your option's value attribute will always be a number.

var json = [{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}];

var options = [], key, value;

json.forEach(function(obj) {
    Object.keys(obj).forEach(function(k) {
        if(typeof obj[k] === "number") {
            key = obj[k];
        }
        else {
            value = obj[k];
        }
    });
    options.push({'key': key, 'value': value}); //or append it directly to select
});

options.forEach(function(option) {
    var option = $('<option>').attr('value', this.key).html(this.value);
    $('#slt').append(option);
});

jsFiddle Demo

A jQuery solution:

$.each(json, function() {
    $.each(this, function(k, v) {
        if(typeof v === 'number') {
            key = v;
        }
        else {
            value = v;
        }
    });
    options.push({'key': key, 'value': value}); ////or append it directly to select
});


$.each(options, function() {
    var option = $('<option>').attr('value', this.key).html(this.value);
    $('#slt').append(option);
});

Upvotes: 1

FarligOpptreden
FarligOpptreden

Reputation: 5043

If I understand correctly, you want to bind dynamic properties to the select? If you can assume that the list of objects will always be returned with a specific amount of properties in a specific order, you can access the properties based on their INDEX.

The following example gets a key and value from an object:

for (var i in myArray) {
    var obj = myArray[i];
    var index = 0;
    var key, val;
    for (var prop in obj) {
        switch (index++) {
            case 0:
                key = obj[prop];
                break;
            case 1:
                val = obj[prop];
                break;
            default:
                break;
        }
    }
    $("select").append("<option value=\"" + key + "\">" + val + "</option>");
}

Upvotes: 1

AlexCheuk
AlexCheuk

Reputation: 5845

in jQuery you can do this:

you can check if the value is a type number, if not then it is a name.

JSFiddle here

var jsonString = '[{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}]';

var json_data = JSON.parse(jsonString);

for(var i = 0; i < json_data.length; i++){

    var option = $("<option>");

    for( var key in json_data[i] ){
        // There should only be two keys, if its a number its ID, else option name
        if( typeof json_data[i][key] === "number" ){
            option.attr("value", json_data[i][key]);
        }else{
            option.html(json_data[i][key]);
        }
    }

    $("select").append(option);

}

Upvotes: 3

iJade
iJade

Reputation: 23801

let jsonArray be your json data, then you can bind the data to a select element using the following code

$.each(jsonArray, function (index, item) {
                 $('#ddl').append($('<option></option>').val(item.JD_No).html(item.JD_Name));
             });

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

Consider that json is the object that array of objects you have in question. Iterate the array, collect each obj, access the keys as you require. Generate an element and store data- attributes equal to the keys in the array.

$.each(json, function(i, obj){
    $('body').append('<select data-no="'+obj.JD_No+'" data-name="'+obj.JD_Name+'"></select>');
});

Upvotes: 0

Related Questions