Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Populate DropDown box with contents of array

This supposed to be really easy but for some reason I cannot find an answer for it online.. I have an array that I receive after AJAX request and I want to populate its content a simple dropdown box. So let's say that's my array:

var workers = ["Steve", "Nancy", "Dave"];

And I have a simple dropdown box which I want to populate dynamically depending what I'll get from an AJAX call:

<div id='dropdown'>
  <select>
  <option value=""></option>
  <option value=""></option>
  <option value=""></option>
  </select>
</div>

How can I do it properly? Thanks a lot!!

like image 638
Pavel Zagalsky Avatar asked Dec 11 '14 19:12

Pavel Zagalsky


1 Answers

Simply create a new Jquery object then append it to the select list. Easier if you just give the select an id instead of the div above it.

for(var i=0; i< workers.length;i++)
{
//creates option tag
  jQuery('<option/>', {
        value: workers[i],
        html: workers[i]
        }).appendTo('#dropdown select'); //appends to select if parent div has id dropdown
}
like image 140
TauterTwiggy Avatar answered Sep 25 '22 21:09

TauterTwiggy