tags:

views:

48

answers:

2

Good Day,

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.

TIA,

coson

A: 

try for loops

var numbers = [1, 2, 3, 4, 5];

for (i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}
Reigel
A: 

Your declaration of array is pretty much an syntax error, the right is:

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)

Fabiano PS