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

但我无法更新下拉列表...

推荐答案

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.

您的代码:

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

Jquery相关问答推荐

DataTables - this.api 用于回调函数中的多个表

ajax调用后Jquery事件不会触发

如何在 jquery 中包含 !important

在 jQuery 事件中控制this的值

如何在 jQuery 中获取浏览器滚动位置?

如何在 Slick 轮播项目之间添加空格

jQuery UI 自动完成宽度未正确设置

如何在 jQuery 中存储全局值(不一定是全局变量)?

如何通过 Select 插件使用 jQuery 验证?

如何在 Jquery 中将 delay() 与 show() 和 hide() 一起使用

在 HTML 表单提交上制作 Enter 键而不是激活按钮

jQuery $.cookie 不是一个函数

为什么使用 jQuery on() 而不是 click()

如何使用 jquery 动态更改 iframe 中的内容?

覆盖 twitter bootstrap Textbox Glow and Shadows

Jquery:如何判断元素是否具有某些 css 类/样式

获取没有在css中设置高度的div的高度

设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

jQuery - 从元素内部 Select 元素

如何使用 jQuery Validation Plugin 以编程方式判断表单是否有效