55

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.

coson
  • 8,301
  • 15
  • 59
  • 84
  • Appending items one at a time on the DOM is considered to be very slow and is highly _not advised_. Way more performatic is to build a string and append it after the loop – Fabiano Soriani Aug 10 '10 at 04:58

8 Answers8

104

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);
fbarikzehy
  • 4,885
  • 2
  • 33
  • 39
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • If the array you are dealing with are not numbers or not from a safe source you should use the 1st technique listed except using `.text(number[i])` instead of `.html(number[i])`. This will ensure you don't risk any injection exploits. – webwake Jul 26 '17 at 13:56
44

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)

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Fabiano Soriani
  • 8,182
  • 9
  • 43
  • 59
8

You can also do this:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 
Cheeso
  • 189,189
  • 101
  • 473
  • 713
4
var qty = 5;
var option = '';
for (var i=1;i <= qty;i++){
   option += '<option value="'+ i + '">' + i + '</option>';
}
$('#items').append(option);
Ed Barahona
  • 721
  • 5
  • 7
4

A solution is to create your own jquery plugin that take the json map and populate the select with it.

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

 $("....").fillValues({datas:your_map,});

Et voila !

You can add functions in your plugin as you like

florex
  • 943
  • 7
  • 9
0

The solution I used was to create a javascript function that uses jquery:

This will populate a dropdown object on the HTML page. Please let me know where this can be optimized - but works fine as is.

function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
{
    var options = '';

    // Create the list of HTML Options
    for (i = 0; i < sourceListObject.List.length; i++)
    {
        options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
    }

    // Assign the options to the HTML Select container
    $('select#' + targetDropDownName)[0].innerHTML = options;

    // Set the option to be Selected
    $('#' + targetDropDownName).val(valueToSelect);

    // Refresh the HTML Select so it displays the Selected option
    $('#' + targetDropDownName).selectmenu('refresh')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
0

Since I cannot add this as a comment, I will leave it here for anyone who finds backticks to be easier to read. Its basically @Reigel answer but with backticks

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);
Seal_Seal
  • 30
  • 6
-1
function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}