I am trying to populate a dropdown select with an array using jQuery.
Here is my code:
// Add the list of numbers to the drop down here var numbers[] = { 1, 2, 3, 4, 5}; $.each(numbers, function(val, text) { $('#items').append( $('<option></option>').val(val).html(text) ); // END
But I'm getting an error. The each function is something I am got off this website.
Is it bombing out because I'm using a one-dimensional array? I want both the option and the text to be the same.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With