Pavel Zagalsky Pavel Zagalsky - 1 year ago 99
HTML Question

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'>
<option value=""></option>
<option value=""></option>
<option value=""></option>

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download