Populate dropdown select with array using jQuery
Solution 1:
Try for loops:
var numbers = [1, 2, 3, 4, 5];
for (var i=0;i<numbers.length;i++){
$('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}
Much better approach:
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
Solution 2:
The array declaration has incorrect syntax. Try the following, instead:
var numbers = [ 1, 2, 3, 4, 5]
The loop part seems right
$.each(numbers, function(val, text) {
$('#items').append( $('<option></option>').val(val).html(text) )
}); // there was also a ) missing here
As @Reigel did seems to add a bit more performance (it is not noticeable on such small arrays)