JQueryUI selectmenu - How to add more options

▼魔方 西西 提交于 2020-01-04 05:00:24

问题


Through javascript how can I add more options to a dropdown selectmenu?

Currently trying the following with no luck:

for (i = 0; i < json.powerDropDownItems.length; i++) {
    //$('#powerSelect').append($("<option></option>").attr("value", json.powerDropDownItems[i]).text(json.powerDropDownItems[i]));
    $('#powerSelect').selectmenu("value", "nice name");
    //$('#powerSelect').appendTo("<option>" + json.powerDropDownItems[i] + "</option>");
}
$('#powerSelect').selectmenu("refresh");​

UPDATE

Thanks to naveen, I got it working (also added code to clear the list). Here is my following code:

 service.getPowerDropDowns(productEC, $('#mountSelect').val(), function (response) {
       var json = $.parseJSON(response.value);

       var options = [];

       // Clear the options first   
       $("#powerSelect option").each(function(index, option) {
            $(option).remove();
       });
        options.push("<option value=''>Choose</option>");
        for (i = 0; i < json.powerDropDownItems.length; i ++)
        {
            options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
        }
        $('#powerSelect').append(options.join("")).selectmenu();
        $('#powerSelect').selectmenu('enable');
    });

回答1:


This will work

$(function() {
    var options = []; 
    for (i = 0; i < json.powerDropDownItems.length; i++) {
        options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
    }
    //append after populating all options
    $('#powerSelect')
        .append(options.join(""))
        .selectmenu();
});​

Demo: http://jsfiddle.net/codovations/p863Q/




回答2:


Depends on the version.

https://github.com/jquery/jquery-ui/tree/selectmenu uses refresh method

https://github.com/fnagel/jquery-ui/tree/selectmenu uses selectmenu() like naveen described.



来源:https://stackoverflow.com/questions/12273176/jqueryui-selectmenu-how-to-add-more-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!