How to add option to select list in jQuery

后端 未结 9 2172
迷失自我
迷失自我 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:39

    For me this one worked

    success: function(data){
                alert("SUCCCESS");
                $.each(data,function(index,itemData){
                    console.log(JSON.stringify(itemData));
                    $("#fromDay").append( new Option(itemData.lookupLabel,itemData.id) )
                });
            }
    
    0 讨论(0)
  • 2020-12-08 18:49

    It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.

    http://www.texotela.co.uk/code/jquery/select/

    var myOptions = {
    "Value 1" : "Text 1",
    "Value 2" : "Text 2",
    "Value 3" : "Text 3"
    } 
    $("#myselect2").addOption(myOptions, false); 
    // use true if you want to select the added options » Run
    
    0 讨论(0)
  • 2020-12-08 18:51

    Don't make your code so complicated. It can be done simply as below by using a foreach-like iterator:

    $.each(buildings, function (index, value) {
        $('#dropListBuilding').append($('<option/>', { 
            value: value,
            text : value 
        }));
    });      
    
    0 讨论(0)
  • 2020-12-08 18:51
    $.each(data,function(index,itemData){
        $('#dropListBuilding').append($("<option></option>")
            .attr("value",key)
            .text(value)); 
    });
    
    0 讨论(0)
  • 2020-12-08 18:52

    Doing it this way has always worked for me, I hope this helps.

    var ddl = $("#dropListBuilding");   
    for (k = 0; k < buildings.length; k++)
       ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");
    
    0 讨论(0)
  • 2020-12-08 18:53

    Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

    You can use the standard Javascript function like this:

    $("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )
    
    0 讨论(0)
提交回复
热议问题