2016-06-09 3 views
0

gespeichert ich dieses Skript leite:Versucht, ein Dropdown mit Optionen zu füllen. Es wird nur ein Wert

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); 
    } 

folgende wählen zu füllen:

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

jedoch nur das letzte Element des Arrays gespeichert ist. Im Debug-Modus scheint das Dropdown-Menü bei jedem Schleifendurchlauf überschrieben zu werden, anstatt ein neues Element hinzuzufügen.

Antwort

3

Derzeit ist der appned Code nicht inside loop, daher wird nur last value zum Dropdown hinzugefügt. Ändere deine Schleife so.

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

Verwenden Sie diesen Code

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); 
    } 
}