Populate dropdown select with array using jQuery

后端 未结 8 1852
花落未央
花落未央 2020-11-29 08:07

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
              


        
相关标签:
8条回答
  • 2020-11-29 08:44

    You can also do this:

    var list = $('#items')[0]; // HTMLSelectElement
    $.each(numbers, function(index, text) { 
        list.options[list.options.length] = new Option(index, text);
    }); 
    
    0 讨论(0)
  • 2020-11-29 08:46

    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)

    0 讨论(0)
提交回复
热议问题