user1471980
user1471980

Reputation: 10626

how do you populate select list with json data in javascript

I am trying to update html select list with json data as shown in this jsfiddle

$("#submitbutton").on("click", function(){


var jsonData=[
    "[{\"id\":1,\"desc\":\"Date\"},{\"id\":2,\"desc\":\"CPU\"}]"
];

var $select = $('#yaxis');
                      $(jsonData).each(function (index, o) {    
                      var $option = $("<option/>").attr("value", o.desc).text(o.desc);
                      $select.append($option);
                    });

                   var $select1 = $('#xaxis');
                      $(jsonData).each(function (index, o) {    
                      var $option1 = $("<option/>").attr("value", o.desc).text(o.desc);
                      $select1.append($option1);
                    });   
});

Any ideas what I am doing wrong here?

Upvotes: 1

Views: 657

Answers (2)

Jason
Jason

Reputation: 4149

You have two issues.

1) JSON isn't being parsed. jQuery.parseJSON (or a Javascript equivalent) will convert it to a string.

2) You have the entire script running onClick of the submit button. I'm assuming that isn't intended behavior.

http://jsfiddle.net/84zugx8p/2/

var jsonData=[
    "[{\"id\":1,\"desc\":\"Date\"},{\"id\":2,\"desc\":\"CPU\"}]"
];

jsonData = jQuery.parseJSON(jsonData);

var $select = $('#yaxis');
$(jsonData).each(function (index, o) {    
    var $option = $("<option/>").attr("value", o.desc).text(o.desc);
    $select.append($option);
});

var $select1 = $('#xaxis');
$(jsonData).each(function (index, o) {    
    var $option1 = $("<option/>").attr("value", o.desc).text(o.desc);
    $select1.append($option1);
});   

Unsure if this is just an example, but it is superfluous to include the JSON string and then parse it within the same file. You could just include it as an object/array. See example below:

var jsonData = [
    {
        id: 1,
        desc: "Date",
    },{
        id: 2,
        desc: "CPU"
    }
];

Upvotes: 0

Manjar
Manjar

Reputation: 3268

You need to parse to json:

var jsonData = JSON.parse("[{\"id\":1,\"desc\":\"Date\"},{\"id\":2,\"desc\":\"CPU\"}]");

JSFiddle updated:

http://jsfiddle.net/84zugx8p/1/

Upvotes: 4

Related Questions