prgrm prgrm - 6 months ago 7
jQuery Question

Trying to fill a dropdown with options. Only a value is stored

I am running this script:

function insertformat(formats){
//Deletes the content of the dropdown if there was any
document.getElementById('format').options.length = 50;
//fills the dropdown with an associative array
for (var key in formats)
var newOption = "<option value='"+key+"'>"+formats[key]+"</option>";
$("#format").append(newOption);
}


to fill the following select:

<select id="format"></select>


However only the last element of the array is stored. In the debug mode it seems that the dropdown is overwritten everytime the loop is finished, instead of adding a new element.

Answer

Currently the appned code is not inside loop so only last value is added to the dropdown. Change your loop like this.

for (var key in formats)
{    
 var newOption = "<option value='"+key+"'>"+formats[key]+"</option>";
 $("#format").append(newOption);
}