javascriptjquery-uijquery-ui-selectmenu

JQueryUI selectmenu - How to add more options


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');
    });

Solution

  • 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/