Chris Mazzochi Chris Mazzochi - 1 year ago 76
jQuery Question

Looping Over An Object And Populating A Select Element With Options and Values

I am trying to populate that '#shuttle-dst' (for shuttle destination) select element in the code below with options based on the values of a given configuration object. This code does what I want it to which is first clear the select element of the options that previously existed, it then loops through the assigned properties of the configs object, and prints to the console just the value of the name properties in this example there were five in this particular configuration:

Admin User
MPR User
States User
All States User

But this code does not populate the select element with all five of the assigned values, just the last one--'All States User'. Why?

function loadConfigurations(configs){
for(var i=0; i < configs.assigned.length; i++){
var item = configs.assigned[i];

$.each(item, function(){
$('#shuttle-dst').html('<option value="' + item.value + '">' + + '</option>');

Answer Source

First, you don't need to call $.each(), since you're already inside the for loop for each item.

To address your issue, you should use append() on your #shuttle-dst element instead of html() (append() adds a new element to the caller element, html() replaces the html of the caller element).

For example:

function loadConfigurations(configs) {
    for (var i=0; i < configs.assigned.length; i++) {
        var item = configs.assigned[i];
            '<option value="' + item.value + '">' + + '</option>'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download