Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

Clear and refresh jQuery Chosen dropdown list

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? :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...