Programmatically create select list
Asked Answered
O

8

51

Does anyone know of a technique to programmatically create an HTML select list including options using JQuery?

Ohara answered 6/7, 2011 at 19:38 Comment(0)
S
136
var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'}
];

var sel = $('<select>').appendTo('body');
$(arr).each(function() {
 sel.append($("<option>").attr('value',this.val).text(this.text));
});
Stope answered 6/7, 2011 at 19:43 Comment(0)
A
13
var s = $('<select/>');
var o = [1, 2, 3];
for (var i in o) {
    s.append($('<option/>').html(o[i]));
}
$('body').append(s);
Allhallowtide answered 6/7, 2011 at 19:41 Comment(0)
I
9

I know this is old, but what the hey:

$selectBox.html($.map(myArray, function(){
    return $('<option/>', {text: this});
}));
Icy answered 17/12, 2013 at 14:53 Comment(1)
Great method for the functional programming paradigm, which we all need to shift to!Rhumb
C
5

This is very straight forward to do:

var selectList = "<select name='numbers'>";
for (var x = 0; x < 10; x++) {
    selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);
Chasechaser answered 6/7, 2011 at 19:44 Comment(0)
F
2

I think it's simpler.IMHO.

 arr.map(x => ($("YOUR SELECTOR").append(`<option value="${x}">${x}</option>`)));
Flatwise answered 13/2, 2019 at 7:40 Comment(0)
T
1

Here's a variation - based on previous answers in this thread - where all but the select-input options can be specified via an input JSON object:

Would be interesting to see if the options array can somehow be specified in that JSON input?

    var fruitListProfile = {
        id : someKey,
        class : 'fruit_list',
        style : 'margin-right: 20px; '
    };

    var selectInput = $('<select/>', fruitListProfile);

    var fruitOptions = ['apple', 'cherry', 'kiwi'];
    for (var i in fruitOptions) {
        selectInput.append($('<option/>').html(fruitOptions[i]));
    }
Tanbark answered 23/3, 2018 at 22:49 Comment(0)
Q
0

If you have already <select> list somewhere in DOM, reuse it and make it empty from previous user interactions...

// Call existing list, chain empty()
var my_list = $("#my_list").empty();
                    
// Build list
$(my_arr).each(function() {
    my_list.append($("<option/>").attr(\'value\',this.item_id).text(this.item_name));
});
Qualify answered 1/7, 2017 at 20:42 Comment(0)
S
0

Here is another version of an answer to the question using ajax to fetch a json response used to create the select list with key value pairs

        $.ajax({
        type: 'post',
        url: 'include/parser.php',
        data: {                     
            mode: 'getSubtypes',
            type: type
        },
        success: function (response) {
            var mySubtype = document.getElementById("Component");
            var components = $.parseJSON(response);

            var selectList = document.createElement("select");
            selectList.id = "subtype";
            selectList.name = "subtype";
            mySubtype.appendChild(selectList);
            $('#subtype').append('<option value="">Select ...</option>');
            $.each(components, function(k, v) {
                var option = new Option(v, k); 
                $('#subtype').append($(option));               
            });
        }
    });        
Skillful answered 4/5, 2018 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.