80

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.

j0k
  • 22,600
  • 28
  • 79
  • 90
James Wilson
  • 5,074
  • 16
  • 63
  • 122

22 Answers22

186

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');
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • That worked like a charm. I had a feeling I was missing something with Chosen. Thank you very much. :) – James Wilson Jul 06 '12 at 15:52
  • Argh, why isn't this in the documentation (or did I just miss it?) Thanks for this. – technomalogical Apr 12 '13 at 00:31
  • @technomalogical - It sure is in [the documentation](http://harvesthq.github.io/chosen/). Just search for **Updating Chosen Dynamically** on that page. – Joseph Silber Apr 12 '13 at 13:55
  • 2
    @JosephSilber It looks like Chosen has made a change, if you want to add this change to your answer to keep all informed since this one is at the top. `.trigger("chosen:updated");` http://harvesthq.github.io/chosen/ – James Wilson Aug 12 '13 at 15:12
  • 5
    I think it's best to do: `.find('option').removeAttr('selected').end().trigger('chosen:updated')`. – cherouvim May 12 '14 at 11:53
  • @cherouvim, the way you mentioned is the best way to have the default placeholder back in list label, thanks a lot! – Samih A Jan 30 '15 at 20:29
  • @cherouvim you deserve more upvotes, as this is the way to get it back to its original state. Thank you! – DanTheMan Feb 11 '15 at 18:56
  • Your answer solved my issue. Thanks. One issue, I have `Select a State` as the `0` index but line here `$(ddl1).val(0).trigger('chosen:updated');` sets it to "Select an Option" and its grayed out. – SearchForKnowledge Apr 15 '15 at 15:48
  • I have an asp.net page and when there is a postback the chosen style gets removed. Is there any way to prevent that. I have the chosen dropdownlist inside an updatepanel. – Si8 May 11 '15 at 14:28
  • @cherouvim perfect! All the other answers will clear the internal value, but still leave the options visually selected. Yours returns it to its full original state, and should be the accepted answer! – Fateh Khalsa Dec 11 '15 at 00:02
  • deserve thumbs up ! – Bhagvat Lande Oct 04 '18 at 11:27
13

The first option should sufice: http://jsfiddle.net/sFCg3/

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

But you have to make sure you are runing this on an event like click of a button or ready or document, like on the jsfiddle.

Also make sure that theres always a value attribute on the option tags. If not, some browsers always return empty on val().

Edit:
Now that you have clarifyed the use of the Chosen plugin, you have to call

$("#autoship_option").trigger("liszt:updated");

after changing the value for it to update the intereface.

http://harvesthq.github.com/chosen/

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69
  • The first option doesn't work. I am guessing because of the Chosen plugin taking control. – James Wilson Jul 06 '12 at 15:49
  • Thanks for editing the answer to make it applicable. I did mention in the original posting that it was for jQuery and Chosen plugin. – James Wilson Jul 06 '12 at 16:43
  • 3
    "Also make sure that theres always a value attribute on the option tags. If not, some browsers always return empty on val()." +1 for this!!! – sskoko Sep 27 '13 at 16:50
8

Try this to reload updated Select box with Latest Chosen JS.

$("#form_field").trigger("chosen:updated");

http://harvesthq.github.io/chosen/

It will Updated chosen drop-down with new loaded select box with Ajax.

Rakesh
  • 756
  • 8
  • 10
  • It doesn't set to 0 but rather the 0 index of chosen which is "Select an Option": http://stackoverflow.com/questions/29653375/how-to-set-asp-net-dropdownlist-index-to-0-from-the-front-end/29655122#29655122 – SearchForKnowledge Apr 15 '15 at 16:02
5

Try this:

$("#autoship_option option[selected]").removeAttr("selected");
Antonio Beamud
  • 2,281
  • 1
  • 15
  • 26
5

I use this:

$('idSelect').val([]);

tested on IE, Safari & Firefox

jrg
  • 63
  • 1
  • 5
5

If you are using chosen, a jquery plugin, then to refresh or clear the content of the dropdown use:

$('#dropdown_id').empty().append($('< option>'))

dropdown_id.chosen().trigger("chosen:updated")

chosen:updated event will re-build itself based on the updated content.

Abin
  • 2,868
  • 1
  • 23
  • 59
2
$('#autoship_option').val('').trigger('liszt:updated');

and set the default option value to ''.

It has to be used with chosen updated jQuery available at this link: https://raw.github.com/harvesthq/chosen/master/chosen/chosen.jquery.min.js.

I spent one full day to find out at the end that jquery.min is different from chosen.jquery.min

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kareem
  • 5,068
  • 44
  • 38
  • so Toni. is your edit just deleting two words of my answer and retyping them back again? what a great edit! – Kareem Jun 20 '13 at 16:34
2

This is more effective than find.

$('select').children('option').first().prop('selected', true)
$('select').trigger("chosen:updated");
Philip
  • 6,827
  • 13
  • 75
  • 104
2
var config = {
      '.chosen-select'           : {},
      '.chosen-select-deselect'  : {allow_single_deselect:true},
      '.chosen-select-no-single' : {disable_search_threshold:10},
      '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
      '.chosen-select-width'     : {width:"95%"}
    }
    for (var selector in config) {
      $(selector).chosen(config[selector]);
    }

Use above config and apply class='chosen-select-deselect' for manually deselect and set the value empty

or if you want deselect option in all combo then apply config like below

var config = {
  '.chosen-select'           : {allow_single_deselect:true},//Remove if you do not need X button in combo
  '.chosen-select-deselect'  : {allow_single_deselect:true},
  '.chosen-select-no-single' : {disable_search_threshold:10},
  '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
  '.chosen-select-width'     : {width:"95%"}
}
for (var selector in config) {
  $(selector).chosen(config[selector]);
}
NIrav Modi
  • 6,038
  • 8
  • 32
  • 47
1
jQuery("#autoship_option option:first").attr('selected', true);
mafafu
  • 1,226
  • 1
  • 17
  • 22
  • This did not work as well. Probably because of the Chosen plugin taking control. – James Wilson Jul 06 '12 at 15:50
  • this works with no plugin.. good stuff. typically you want to reset to the first option, which is what this does (and doesn't clear the default text from the drop down list). – Phillip Holmes Jul 24 '15 at 16:44
1

I am not sure if this applies to the older version of chosen,but now in the current version(v1.4.1) they have a option $('#autoship_option').chosen({ allow_single_deselect:true }); This will add a 'x' icon next to the name selected.Use the 'x' to clear the 'select' feild.

PS:make sure you have 'chosen-sprite.png' in the right place as per the chosen.css so that the icons are visible.

Harsh Gupta
  • 444
  • 3
  • 9
1

In Chrome version 49

you need always this code

$("select option:first").prop('selected', true)

Diogo Cid
  • 3,764
  • 1
  • 20
  • 25
0

i think you have to assign a new value to the select, so if you want to clear your selection you probably want to assign it to the one that has value = "". I think that you will be able to get it by assigning the value to empty string so .val('')

Nir
  • 356
  • 1
  • 5
0

HTML:

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

JS:

$('#rs').on('click', function(){
    $('autoship_option').find('option:selected').removeAttr('selected');
});

Fiddle: http://jsfiddle.net/Z8nE8/

bancer
  • 7,475
  • 7
  • 39
  • 58
0

You can try this to reset (empty) drop down

 $("#autoship_option").click(function(){
            $('#autoship_option').empty(); //remove all child nodes
            var newOption = $('<option value=""></option>');
            $('#autoship_option').append(newOption);
            $('#autoship_option').trigger("chosen:updated");
        });
Naresh Ramoliya
  • 770
  • 2
  • 8
  • 25
0

The new Chosen libraries don't use the liszt. I used the following:

document.getElementById('autoship_option').selectedIndex = 0;
$("#autoship_option").trigger("chosen:updated");
ter24
  • 462
  • 7
  • 17
0

If you need to have first option selected by no matter of its value (sometimes first option value is not empty) use this:

$('#autoship_option').val($('#autoship_option option:first-child').val()).trigger("liszt:updated");

It will get value of first option and set it as selected then trigger update on Chosen. So it work like reset to first option on list.

Artur Stępień
  • 466
  • 3
  • 18
0

Exactly i had the same requirement. But resetting the drop down list by setting simply empty string with jquery won't work. You should also trigger update.

Html:
<select class='chosen-control'>
<option>1<option>
<option>2<option>
<option>3<option>
</select>

Jquery:
$('.chosen-control').val('').trigger('liszt:updated');

sometimes based on the version of chosen control you are using, you may need to use below syntax.

$('.chosen-control').val('').trigger("chosen:updated");

Reference: How to reset Jquery chosen select option

0
jQuery('.chosen-processed').find('.search-choice-close').click();
vard
  • 4,057
  • 2
  • 26
  • 46
0

Simple add trigger change like this:

$('#selectId').val('').trigger('change');
buidan
  • 1
  • 1
0

from above solutions, Nothing worked for me. This worked:

$('#client_filter').html(' '); //this worked

Why is that? :)

$.ajax({ 
        type: 'POST', 
        url: xyz_ajax,
        dataType: "json",
        data : { csrfmiddlewaretoken: csrftoken,
                instancess : selected_instances }, 
        success: function(response) { 
            //clear the client DD       
            $('#client_filter').val('').trigger('change') ; //not working
            $('#client_filter').val('').trigger('chosen:updated') ; //not working
            $('#client_filter').val('').trigger('liszt:updated') ; //not working
             $('#client_filter').html(' '); //this worked
             jQuery.each(response, function(index, item) {
                  $('#client_filter').append('<option value="'+item.id+'">' + item.text + '</option>');
                });                 
           $('#client_filter').trigger("chosen:updated");
        }
      });
     } 
Deepa MG
  • 188
  • 1
  • 15
0

You can try this to add dynamically from drop down, if u know the dropdown index key

$('select').find('option:nth-child(5)')
.prop('selected', true).end()
.trigger('chosen:updated');
Prakash Sah
  • 41
  • 1
  • 3