I'm trying to clear jQuery Chosen dropdown list and refresh it.
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>
When I click "Refresh" button, it should turn into this:
<select data-placeholder="Select Picture..." class="chosen-select" style="width:250px;" id="picturegallery" tabindex="2">
<option value="1">test</option>
</select>
What I have tried:
$("#refreshgallery").click(function(){
$('#picturegallery').empty();
var newOption = $('<option value="1">test</option>');
$('#picturegallery').append(newOption);
});
But I can't get it to update that dropdown list... Some help? :)
Using .trigger("chosen:updated");
you can update the options list after appending.
Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.
Your code:
$("#refreshgallery").click(function(){
$('#picturegallery').empty(); //remove all child nodes
var newOption = $('<option value="1">test</option>');
$('#picturegallery').append(newOption);
$('#picturegallery').trigger("chosen:updated");
});
If trigger("chosen:updated");
not working, use .trigger("liszt:updated");
of @Nhan Tran it is working fine.
$("#idofBtn").click(function(){
$('#idofdropdown').empty(); //remove all child nodes
var newOption = $('<option value="1">test</option>');
$('#idofdropdown').append(newOption);
$('#idofdropdown').trigger("chosen:updated");
});
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");
});
}
来源:https://stackoverflow.com/questions/20148195/clear-and-refresh-jquery-chosen-dropdown-list