3

Im trying to populate a dropdown menu with the data returned from database. my HTML is:

 <select class="Input"></select>       

Once I query my db, Im trying to append the data to the drop down.

$(".Input").append(data[0].abc);

Here "data[0].abc" refers to the first value of the array. abc is the field name of the value being returned. In case of more than one values for that particular field name, I plan to have a for loop which will loop through the entire array and append each value and add it to the drop down. I get the values but cant seem to add them to the drop down. Please correct me if my thought process is wrong. Can someone point me in the right direction? Thank you.

pal
  • 105
  • 1
  • 3
  • 17
  • Please read this: http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist-using-jquery – spooky Feb 04 '15 at 20:43

2 Answers2

3

Try this:

$('.Input').append('<option>' + data[0].abc  + '</option');
Caner Akdeniz
  • 1,862
  • 14
  • 20
1

To clarify on top of @Caner's answer, it is by far WAY faster to add those to a string, and then append it to the dropdown only once. I cannot tell you how many times I see this being done. I don't have a timeline of it, but trust me.

var options = '';
$.each(data, function(index, value) {
    options += '<option value="' + value.abc + '" text="' + value.abc + '" />';
});

$('.Input').append(options);

Pretty good explanation here: Which is better: string html generation or jquery DOM element creation?

Community
  • 1
  • 1
Rob Scott
  • 7,921
  • 5
  • 38
  • 63