user1955041
user1955041

Reputation: 35

Parsing an array Json to select Tag

I have a Json response. I need to take each value and append them to the Select tag. Each value separated by comma should be appended as a option in select tag.

Code is :

Jquery:

var dec ={"dc":["One","Two","Three"]};

jQuery.each(dec, function(index, value) {

    $(".request").append("<option value='" + index + "'>" + value + "</option>");  

});

HTML:

<select class="request">

</select>

The above code is appending everything to a single option but not as different options in select tag

Upvotes: 1

Views: 644

Answers (3)

Yatrix
Yatrix

Reputation: 13775

var $opt;

For (var i = 0; i < dec.dc.length; i++) {
    $opt = $('<option></option>');
    $opt.text(dec.dc[i]);
    $opt.val(i);
    $('.request').append($opt);
}

Do a basic js loop when you can, they're faster.

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

try like this

var dec ={"dc":["One","Two","Three"]};
var html = "";
jQuery.each(dec, function(index, value) {

    html += "<option value='" + index + "'>" + value + "</option>";  
});

 $(".request").html( html );

Upvotes: 1

Justin Helgerson
Justin Helgerson

Reputation: 25521

You need to iterate over the dc array. Right now you have an object, dec with a child array dc.

jQuery.each(dec.dc, function(index, value) {
    $(".request").append("<option value='" + index + "'>" + value + "</option>");  
});

Upvotes: 0

Related Questions