Lokendra Panwar Lokendra Panwar - 6 months ago 43
Ajax Question

How to display data in select box option using jquery

I want to display data in select box option from ajax response.

here is my view file

<select class="form-control" name="vendor" id="vendor_list" required style="width: 159px;">
<option value="">Vendor 1</option>
</select>


Here is my ajax success function

success: function(data) {
$.each(data, function(i, value) {
console.log(value);
$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
console.log(value);
});
}


here is my ajax response json data

[{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]


How to display value in select box.
giv me suggestion.thanks

Answer

I think the problem is with

$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');

It will be much better if you create a option string & append it after entire data has been iterated

Since it is not possible to replicate the ajax , so I have directly use the ajax response

You can put the entire code inside success block , but you will not need var x because data will play role of var x=[...] in your case

var x = [{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]
var _options =""
$.each(x, function(i, value) {
        _options +=('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
    });
$('#vendor_list').append(_options);

Check this jsFiddle