Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate dropdown select with array using jQuery

Tags:

jquery

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.

like image 282
coson Avatar asked Aug 10 '10 04:08

coson


2 Answers

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); 
like image 60
Reigel Avatar answered Sep 23 '22 02:09

Reigel


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)

like image 43
Fabiano Soriani Avatar answered Sep 22 '22 02:09

Fabiano Soriani