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
682 views
in Technique[技术] by (71.8m points)

How do I reset a jquery-chosen select option with jQuery?

I have tried numerous things and nothing seems to be working.

I am using jQuery and Chosen plugin.

Methods I have tried:

var select = jQuery('#autoship_option');

select.val(jQuery('options:first', select).val());

jQuery('#autoship_option').val('');

jQuery('#autoship_option').text('');

jQuery('#autoship_option').empty('');

jQuery("#autoship_option option[value='']").attr('selected', true);

It always shows the Active Autoship option once it has been selected. I can't seem to get it to clear the selection.

Here is the select box:

<select id="autoship_option" data-placeholder="Choose Option..." 
style="width: 175px;" class="chzn-select">
    <option value=""></option>
    <option value="active">Active Autoship</option>
</select>

Anyone familiar with Chosen and being able to clear a select box with one option? (It will have more options in the future.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Setting the select element's value to an empty string is the correct way to do it. However, that only updates the root select element. The custom chosen element has no idea that the root select has been updated.

In order to notify chosen that the select has been modified, you have to trigger chosen:updated:

$('#autoship_option').val('').trigger('chosen:updated');

or, if you're not sure that the first option is an empty string, use this:

$('#autoship_option')
    .find('option:first-child').prop('selected', true)
    .end().trigger('chosen:updated');

Read the documentation here (find the section titled Updating Chosen Dynamically).


P.S. Older versions of Chosen use a slightly different event:

$('#autoship_option').val('').trigger('liszt:updated');

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

...