2013-11-22 60 views
55

我想清除jQuery選擇下拉列表並刷新它。清除和刷新jQuery選擇下拉列表

HTML:

<select data-placeholder="Select Picture..." class="chosen-select" style="width:250px;" id="picturegallery" tabindex="2"> 
    <option value="" selected="selected"></option> 
    <option value="x">remove me</option> 
</select> 

當我點擊 「刷新」 按鈕,它應該變成這樣:

<select data-placeholder="Select Picture..." class="chosen-select" style="width:250px;" id="picturegallery" tabindex="2"> 
    <option value="1">test</option> 
</select> 

我曾嘗試:

$("#refreshgallery").click(function(){ 
    $('#picturegallery').empty(); 
    var newOption = $('<option value="1">test</option>'); 
    $('#picturegallery').append(newOption); 
}); 

但我可以」噸得到它來更新下拉列表... 有些幫助? :)

+0

是您在DOM代碼準備好了嗎? –

+1

是的,它是(太短的評論,隨機文本) – plexcell

回答

131

使用.trigger("chosen:updated");您可以在追加後更新選項列表。

更新獲選動態:如果您需要在您的選擇字段更新選項,並要選擇拿起變化,你會 需要觸發「選擇:更新」上田事件。選定的 將基於更新後的內容重新構建。

您的代碼:

$("#refreshgallery").click(function(){ 
     $('#picturegallery').empty(); //remove all child nodes 
     var newOption = $('<option value="1">test</option>'); 
     $('#picturegallery').append(newOption); 
     $('#picturegallery').trigger("chosen:updated"); 
    }); 
+3

是的... .html()打破了選擇的組合。 –

+2

謝謝,我正在尋找這個解決方案 – logudotcom

+0

YOU SAVED MY LIFE :) –

0

MVC 4:

function Cargar_BS(bs) { 
     $.getJSON('@Url.Action("GetBienServicio", "MonitoreoAdministracion")', 
         { 
          id: bs 
         }, 
         function (d) { 
          $("#txtIdItem").empty().append('<option value="">-Seleccione-</option>'); 
          $.each(d, function (idx, item) { 
           jQuery("<option/>").text(item.C_DescBs).attr("value", item.C_CodBs).appendTo("#txtIdItem"); 
          }) 
          $('#txtIdItem').trigger("chosen:updated"); 
         }); 
    } 
0
$("#idofBtn").click(function(){ 
     $('#idofdropdown').empty(); //remove all child nodes 
     var newOption = $('<option value="1">test</option>'); 
     $('#idofdropdown').append(newOption); 
     $('#idofdropdown').trigger("chosen:updated"); 
    }); 
+0

請花點時間並描述此代碼如何解決問題。 – 31piy