How to add option to select list in jQuery

后端 未结 9 2173
迷失自我
迷失自我 2020-12-08 18:27

My select list is called dropListBuilding. The following code does not seem to work:

 for (var i = 0; i < buildings.length; i++) {
     var v         


        
相关标签:
9条回答
  • 2020-12-08 18:53

    This is working fine, try out this.

    var ob = $("#myListBox");
    
    for (var i = 0; i < buildings.length; i++) {
         var val = buildings[i];
         var text = buildings[i];
    
         ob.prepend("<option value="+ val +">" + text + "</option>");
    }
    
    0 讨论(0)
  • 2020-12-08 19:00

    If you do not want to rely on the 3.5 kB plugin for jQuery or do not want to construct the HTML string while escapping reserved HTML characters, here is a simple way that works:

    function addOptionToSelectBox(selectBox, optionId, optionText, selectIt)
    {
        var option = document.createElement("option");
        option.value = optionId;
        option.text = optionText;
        selectBox.options[selectBox.options.length] = option;
        if (selectIt) {
            option.selected = true;
        }
    }
    
    var selectBox = $('#veryImportantSelectBox')[0];
    addOptionToSelectBox(selectBox, "ID1", "Option 1", true);
    
    0 讨论(0)
  • 2020-12-08 19:01
    $('#dropListBuilding').append('<option>'+val+'</option>');
    
    0 讨论(0)
提交回复
热议问题