简体   繁体   中英

Populate select menu with options from array

I'm having issues populating my select menu with options from array using this approach

var adultAgesArr = ['18 - 20', '21 - 30', '31 - 40', '41 - 50', '51 - 60', '60 +'];
var $ageOptions = '';
$.each(adultAgesArr, function(index, value){
    $ageOptions += $('<option/>', {text: value});
})

and after

$('<select/>').append($ageOptions)

what I get as a result is

<select>
[Object object] [Object object] [Object object] [Object object] [Object object] [Object object]
</select>

You could do this:

$select = $('select');
$.each(adultAgesArr, function(index, value){
  $select.append($('<option/>', {text: value, value: value}));
})

Before it appeared that you were coercing the jQuery objects to a string. I think this way, if you cache select beforehand, is just as efficient.

DEMO

Hope this helps:

<select id="menu"></select>

var populate = function() {
    var adultAgesArr = ['18 - 20', '21 - 30', '31 - 40', '41 - 50', '51 - 60', '60 +'],
    select = $('#menu')[0];

    $.each(adultAgesArr, function(index, value){
        var opt = document.createElement('option');
        opt.value = value;
        opt.innerHTML = value;
        select.appendChild(opt);
    });
}

populate();

For creating an option instead of doing this:

 $ageOptions += $("< option/>", {text: value});

Is better to do this:

 new Option("option text", "value")

then append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM