3

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

7
  • What is your issue ? I see nothing wrong in your code. Commented May 30, 2016 at 9:11
  • What is the error that you are getting? This code looks fine. If there are multiple responses as shown in your ajax response code, adding the options using a loop. Commented May 30, 2016 at 9:11
  • I am getting following error--morris.js (line 79, col 15) TypeError: invalid 'in' operand e Commented May 30, 2016 at 9:12
  • Try running each on JSON.parse(data) Commented May 30, 2016 at 9:16
  • well it's coming from morris.js we don't even know what that is. I don't think we can help you with the shared code. Commented May 30, 2016 at 9:17

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.