Programmatically create select list

后端 未结 8 2199
不知归路
不知归路 2020-11-29 02:48

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

相关标签:
8条回答
  • 2020-11-29 03:13

    I know this is old, but what the hey:

    $selectBox.html($.map(myArray, function(){
        return $('<option/>', {text: this});
    }));
    
    0 讨论(0)
  • 2020-11-29 03:14
    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));
    });
    
    0 讨论(0)
  • 2020-11-29 03:14
    var s = $('<select/>');
    var o = [1, 2, 3];
    for (var i in o) {
        s.append($('<option/>').html(o[i]));
    }
    $('body').append(s);
    
    0 讨论(0)
  • 2020-11-29 03:22

    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]));
        }
    
    0 讨论(0)
  • 2020-11-29 03:28

    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);
    
    0 讨论(0)
  • 2020-11-29 03:29

    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));               
                });
            }
        });        
    
    0 讨论(0)
提交回复
热议问题