Reset select2 value and show placeholder
Asked Answered
Z

45

275

How do I set the placeholder on value reset by select2. In my example If locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder. This script is resetting the value but won't show the placeholder

$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});
Zelikow answered 30/7, 2013 at 20:46 Comment(2)
Just refer to the Documentation instead of using weird suggestions which wont work from this or other SO threads. The suggested approach by Select2 is: $('#mySelect2').val(null).trigger('change');. Reference: select2.org/programmatic-control/add-select-clear-items. And that works like a charm.Pippa
incase if any one needs full implementation with ajax codepen.io/ashgadala/pen/NWOxBzeOra
H
260

You must define the select2 as

$("#customers_select").select2({
    placeholder: "Select a customer",
    initSelection: function(element, callback) {                   
    }
});

To reset the select2

$("#customers_select").select2("val", "");
Hsiuhsu answered 22/10, 2013 at 14:11 Comment(12)
I tried this with a <select multiple>, but I get the error: Option 'initSelection' is not allowed for Select2 when attached to a <select> element.Fifth
This does not work for me. The placeholder still does not show up.Timmerman
$("#customers_select").select2("val", ""); working for me :DIveyivie
See @Lego Stormtroopr's answer below, which reflects the new method according to Select2's API. The above method is deprecated.Coping
As of v4.0.3, it doesn't seem like .select2("val", "") works anymore.Needlefish
$("#selectId").empty().select2();Levina
@Danilo it clears all the values from the drop down if you try to search / select another value ,Camarata
$("#customers_select").select2({ data: " ", placeholder: "Select a customer" });Tandie
$("#customers_select").select2("data", null);Leatherwood
$("#customers_select").val('').trigger('change') ; I used this and it worked.Dipteran
$("#selectId").empty().select2() works for me also - but I still can't reset to placeholder textMucronate
@Needlefish how can I do it without triggering it.Achievement
A
204

The accepted answer does not work in my case. I'm trying this, and it's working:

Define select2:

$("#customers_select").select2({
    placeholder: "Select a State",
    allowClear: true
});

or

$("#customers_select").select2({
    placeholder: "Select a State"
});

To reset:

$("#customers_select").val('').trigger('change')

or

$("#customers_select").empty().trigger('change')
Alika answered 3/3, 2016 at 13:33 Comment(11)
I found that unless you have the placeholder defined the allowClear does not workOvervalue
Neither $('#your_select_input').val('').trigger('change') nor $('#your_select_input').val(''); doesn't work in FirefoxCrystacrystal
this works for me, it deletes all data from the select2 I'm using v4.0.3Aedes
$("#customers_select").empty().trigger('change') works for me. :)Tubuliflorous
@Alika Thanks. I was explicitly appending the values into my select2, so ".val('')" was not working. Then I saw "empty" in your answer and I realized that I need to use "empty" and it worked. Thanks again.Garland
For some reason . . . only the empty().trigger('change') worked . . .Demeter
'$("#customers_select").empty().trigger('change')' worked for me, thanks!Plaque
this one works pretty well $("#customers_select").empty().trigger('change')Malar
$("#customers_select").val('').trigger('change') worked for me. :) Thanks!Leeward
I tried with .val(null) and didn't work, but .empty() works great! :DSate
allowClear: true worked as expected.Mcandrew
U
135

Select2 has changed their API:

Select2: The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.

The best way to do this now is:

$('#your_select_input').val('');

Edit: December 2016 Comments suggest that the below is the updated way to do this:

$('#your_select_input').val([]);
Usury answered 2/2, 2015 at 4:57 Comment(14)
This updates the value, but for it to show up correctly, you'll have to trigger a change event. $('#your_select_input').val('').trigger('change')Lipoprotein
This does not work for me. The placeholder still does not show up.Timmerman
This works for me with the change trigger addition, but also triggers the validation library we're using--for now I'll have to use the deprecated version.Simply
This does not work correctly, using select2 4.0.2. It will reset the selection and restore the placeholder, but when I choose a new value (post reset), I also see selected an "empty string" option (i.e., a box with only an "x" in it).Staurolite
@Staurolite i am facing same issue. did you find the fix for this?Darren
$('#your_select_input').val('').trigger('change') works only when placeholder is provided. else empty string option will be displayed as selected option.Darren
Neither $('#your_select_input').val('').trigger('change') nor $('#your_select_input').val(''); doesn't work in FirefoxCrystacrystal
Shouldn't this be val([])?Tithe
@Tithe maybe - I haven't had a chance to test it. If val([]) works, feel free to update the answer.Usury
The $().val([]) worked for me when nothing else would. This seems to be the current answer.Bogeyman
The correct way (see the code for the "clear" button: select2.github.io/examples.html#programmatic) is to set the value to null and trigger the change event: $('#your_select_input').val(null).trigger('change'); If you don't want bound change listeners to run (i.e. silently change the value) then trigger change.select2 instead (github.com/select2/select2/issues/3620)Filide
as @amol said,we need to trigger change,if not,the selected options are cleared,but there are seleted in the select input.Vlissingen
$('#your_select_input').val([]).trigger('change'); did the job for meDifferentiable
Late to the party, but for this to work, you need an empty <option> first, even if you use data argument. (have not tried with ajax).Salbu
H
68

The only thing can work for me is:

$('select2element').val(null).trigger("change")

I'm using version 4.0.3

Reference

According to Select2 Documentation

Heeheebiejeebies answered 27/2, 2017 at 7:31 Comment(2)
I'm also using v4.0.3 and $('select2element').val("").trigger("change") is working fine too.Huntington
Please note that you must also have an empty <option> inside your <select>. If you are using ajax with select2, this will help - $('#selectFieldId').prepend('<option selected="selected"></option>')Mismate
A
45

With Select2 version 4.0.9 this works for me:

$( "#myselect2" ).val('').trigger('change');
Aulos answered 27/8, 2019 at 1:54 Comment(2)
This made my select2 dropdown blank. Worked for me. Thanks.Osteophyte
Worked for me for version 4.0.13Worldly
P
19

Select2 uses a specific CSS class, so an easy way to reset it is:

$('.select2-container').select2('val', '');

And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

Preglacial answered 1/11, 2014 at 15:42 Comment(0)
S
18

I know this is kind of an old question, but this works for the select2 version 4.0

 $('#select2-element').val('').trigger('change');

or

$('#select2-element').val('').trigger('change.select2'); 

if you have change events bound to it

Sphygmograph answered 2/3, 2017 at 2:42 Comment(1)
Excellent solution. I had to add .last() function to target the newly added select2 box. $('#select2-element').last().val('').trigger('change.select2'); Philippi
A
17

Use this :

$('.select').val([]).trigger('change');
Anemology answered 29/9, 2017 at 7:20 Comment(2)
For me, worked with $('.select2').val([]).trigger('change');Phenazine
I've tried all the suggestions above but none worked for me. This is worked perfectly for me. thanks!Leif
S
15

TO REMOVE SELECTED VALUE

$('#employee_id').select2('val','');

TO CLEAR OPTION VALUES

$('#employee_id').html('');
Spiegleman answered 23/7, 2015 at 7:52 Comment(4)
fefe is asking for re-setting the placeholder text. So only the first part of this answer is valid.Lactoflavin
Yes that's why i highlight the answers title.Spiegleman
The first answer indeed it isn't applying anymore from >4.0. But the second option saved me! This is the solution when you want to really clear the select2. Just setting the .val('') to select 2 it isn't enough. You need also to clear the html. Thanks a lot!!!Clementinaclementine
any way thanks @ShankaSMS I was looking for solution to reset and rebind the data to select2Mera
H
9

This is the correct way:

 $("#customers_select").val('').trigger('change');

I am using the latest release of Select2.

Hyperactive answered 28/3, 2018 at 10:26 Comment(0)
I
8

I tried the above solutions but it didn't work for me.

This is kind of hack, where you do not have to trigger change.

$("select").select2('destroy').val("").select2();

or

$("select").each(function () { //added a each loop here
        $(this).select2('destroy').val("").select2();
});
Intra answered 12/4, 2017 at 10:47 Comment(1)
I modified to something like in my implementation: $("#select").on('change', function () { $(this).val("").select2(); });Hypophyge
W
8

Use following to configure select2

    $('#selectelementid').select2({
        placeholder: "Please select an agent",
        allowClear: true // This is for clear get the clear button if wanted 
    });

And to clear select input programmatically

    $("#selectelementid").val("").trigger("change");
    $("#selectelementid").trigger("change");
Wille answered 2/8, 2017 at 12:5 Comment(0)
R
6

You can clear te selection by

$('#object').empty();

But it wont turn you back to your placeholder.

So its a half solution

Riba answered 26/1, 2017 at 20:23 Comment(0)
S
6

Firstly you must define select2 like this:

$('#id').select2({
    placeholder: "Select groups...",
    allowClear: true,
    width: '100%',
})

To reset select2, simply you may use the following code block:

$("#id > option").removeAttr("selected");
$("#id").trigger("change");
Stalwart answered 23/7, 2017 at 22:8 Comment(0)
P
5

For users loading remote data, this will reset the select2 to the placeholder without firing off ajax. Works with v4.0.3:

$("#lstProducts").val("").trigger("change.select2");
Procession answered 31/7, 2017 at 23:11 Comment(2)
Worked for me but my trigger was just 'change'Barcus
This was the only solution that worked for me to reset a Select2 from another Select2 using Ajax data.Aulos
P
5

So, to reset the form some of you will have a reset button. Add the following code inside the script tag

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
    $("#select_field_id").select2({
    placeholder: "this is a placeholder",
    });
});

Or just to empty select field without keeping a placeholder:

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
 });
Philpot answered 27/8, 2019 at 13:26 Comment(0)
A
3

as of v.4.0.x...

to clear the values, but also restore the placeholder use...

.html('<option></option>');  // defaults to placeholder

if it's empty, it will select the first option item instead which may not be what you want

.html(''); // defaults to whatever item is first

frankly...Select2 is such a pain in the butt, it amazes me it hasn't been replaced.

Antitrust answered 4/7, 2017 at 2:23 Comment(0)
T
3

For the place holder

$("#stateID").select2({
    placeholder: "Select a State"
});

To reset a select 2

$('#stateID').val('');
$('#stateID').trigger('change');

Hope this helps

Tertias answered 9/5, 2018 at 6:22 Comment(0)
C
3

From select2 website,

$("#mySelect2ControlId").val(null).trigger("change");
Coker answered 13/5, 2020 at 23:48 Comment(0)
C
2

Following the recommended way of doing it. Found in the documentation https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder (this seems to be a fairly common issue):

When this happens it usually means that you do not have a blank <option></option> as the first option in your <select>.

as in:

<select>
   <option></option>
   <option value="foo">your option 1</option>
   <option value="bar">your option 2</option>
   <option value="etc">...</option>
</select>
Cowbird answered 15/3, 2016 at 14:40 Comment(0)
G
2

I was also having this problem and it stems from val(null).trigger("change"); throwing a No select2/compat/inputData error before the placeholder gets reset. I solved it by catching the error and setting the placeholder directly (along with a width). Note: If you have more than one you will need to catch each one.

try{
    $("#sel_item_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
try{
    $("#sel_location_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
$('.select2-search__field')[0].placeholder='All Items';
$('.select2-search__field')[1].placeholder='All Locations';
$('.select2-search__field').width(173);

I'm running Select2 4.0.3

Godin answered 22/11, 2016 at 16:9 Comment(1)
It sounds like you have a listener bound to the change event. Try triggering change.select2 - that won't trigger bound listeners (see github.com/select2/select2/issues/3620).Filide
A
2

I have tried above solutions but none worked with version 4x.

What i want to achieve is: clear all options but don't touch the placeholder. This code works for me.

selector.find('option:not(:first)').remove().trigger('change');
Austerity answered 14/3, 2017 at 13:26 Comment(1)
If you use selector.find('option:not(:first)').html(''); it should work.Clementinaclementine
E
2

After trying the first 10 solutions here and failing, I found this solution to work (see "nilov commented on Apr 7 • edited" comment down the page):

(function ($) {
   $.fn.refreshDataSelect2 = function (data) {
       this.select2('data', data);

       // Update options
       var $select = $(this[0]);
       var options = data.map(function(item) {
           return '<option value="' + item.id + '">' + item.text + '</option>';
       });
       $select.html(options.join('')).change();
   };
})(jQuery);

The change is then made:

var data = [{ id: 1, text: 'some value' }];
$('.js-some-field').refreshDataSelect2(data);

(The author originally showed var $select = $(this[1]);, which a commenter corrected to var $select = $(this[0]);, which I show above.)

Expunge answered 27/7, 2017 at 20:24 Comment(1)
this is the only one that worked for me... years laterJovi
S
2

Use this code into your js file

$('#id').val('1');
$('#id').trigger('change');
Sandglass answered 10/9, 2018 at 6:1 Comment(0)
J
2
$("#customers_select").val([]).trigger('change')

this will remove values AND most important for me - it also remove an empty x button

Judon answered 25/5, 2020 at 21:45 Comment(0)
L
2

This is working snippet for latest select 2 api.

Reset or Clear select2 input.

$("#selector").val([]).trigger('change');

i.e.

$( ".reset" ).on('click',function(){
    $(".select2input").val([]).trigger('change');
});
Levon answered 5/1, 2022 at 11:29 Comment(0)
V
2

Admin lte 3 with Select2.

After a lot of tries this is what worked for me :

Library at the top ( Modify position if it's conflicting with the bootstrap )

<link rel="stylesheet" href="/template/almasaeed2010/adminlte/plugins/select2/css/select2.min.css" >
<link rel="stylesheet" href="/template/almasaeed2010/adminlte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css" >

JS scripts ( After JQuery and before your .select2(... script )

<script src="/template/almasaeed2010/adminlte/plugins/select2/js/select2.full.min.js"></script>

HTML

<select name="mode_de_reglement" id="mode_de_reglement" >
     <option value="cheque">cheque</option>
     <option value="virement">virement</option>
     <option value="carte_bancaire">carte bancaire</option>
</select>

Initialization script :

$("#mode_de_reglement").select2({
     placeholder : "Mode de réglement"
});
$('#mode_de_reglement').val('');//setting starting value to empty because by default it selects the first value
$('#mode_de_reglement').trigger('change');//change to let the select2 library know you modified the value programmatically

Finally whenever the form gets reopened i refresh the select again using :

//... onclick="openModalNewRecord()"
$('#mode_de_reglement').val('');
$('#mode_de_reglement').trigger('change');

Here is the template i used AdminLte3

Also note that you can create select2 using

$("#mode_de_reglement").select2({
     placeholder : "Mode de réglement" ,
     allowClear : true 
});

Allow clear adds an X button to clear selection and show placeholder , but i don't use it unless that field is nullable in the database.

Victorious answered 18/3, 2022 at 16:13 Comment(1)
Note: Don't forget to set style="width: 100% ;" or the select 2 will be collapsed !Victorious
P
2
$(your_id_or_class).select2("data",null);

This will actually clear it without adding a new blank option, making the select2 field clearable, or triggering any callbacks from the change. It behaves the most like a true reset of the dropdown.

Pregnancy answered 29/3, 2023 at 7:1 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Ream
D
1

Well whenever I did

$('myselectdropdown').select2('val', '').trigger('change');

I started getting some kind of lag after some three to four triggers. I suppose there's a memory leak. Its not within my code because if I do remove the this line, my app is lag free.

Since I have allowClear options set to true, I went with

$('.select2-selection__clear').trigger('mousedown');

This can be followed by a $('myselectdropdown').select2('close'); event trigger on the select2 dom element in case you wanna close the open suggestion drop down.

Denice answered 29/8, 2016 at 5:58 Comment(0)
T
1

Using select2 version 3.2 this worked for me:

$('#select2').select2("data", "");

Didn't need to implement initSelection

Triumphant answered 29/4, 2017 at 17:32 Comment(1)
This was by far the simplest way for me to do it. The other methods did not work for me.Nephralgia
C
1
$('myselectdropdown').select2('val', '0')

where 0 is your first value of the dropdown

Cortez answered 9/1, 2018 at 9:56 Comment(0)
L
1

If you want to clear all select2 inputs when closing a modal for instance then you can add a class "select2" and set them all back to their place holders like so.

$('#myModal').on('hidden.bs.modal', function (e) {
    $(this)
        .find(".select2").select2({placeholder: "Choose an option"})
        .val('').trigger('change.select2');
});

This approach of resetting all at once can be used for forms either. The version is which this is working for me is 4.0.10

Laminitis answered 5/5, 2020 at 20:23 Comment(0)
S
1

This solution work for me (Select2 4.0.13)

$('#select').on("select2:unselecting", function (e) {
   $(this).val('').trigger('change');
   e.preventDefault();
});
Spectatress answered 17/8, 2020 at 14:25 Comment(0)
D
0

Before you clear the value using this $("#customers_select").select2("val", ""); Try setting focus to any other control on reset click.

This will show the placeholder again.

Downturn answered 12/8, 2015 at 15:13 Comment(0)
G
0

The DOM interface, already keeps track of the initial state...

So doing the following is enough:

$("#reset").on("click", function () {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });
});
Godown answered 21/6, 2016 at 9:27 Comment(0)
A
0

One [very] hacky way to do it (I saw it work for version 4.0.3):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});
  • allowClear must be set to true
  • an empty option must exist in the select element
Assistance answered 31/8, 2016 at 18:38 Comment(0)
A
0

In order to reset the values and the placeholder I just reinitiate the select2 element:

$( "#select2element" ).select2({
    placeholder: '---placeholder---',
    allowClear: true,
    minimumResultsForSearch: 5,
    width:'100%'
});
Arun answered 3/2, 2017 at 14:55 Comment(2)
Rebuilding a house to clean a sink is not really a solution.Lainelainey
Very true, @Lainelainey , but when the control doesn't provide a clean way to reset itself without calling the "change" event, you have to do what you have to do without hacking the control, unfortunately. I have validation listeners running on the change event for the select elements. Triggering the change event validates and show an error message that doesn't need to bee seen on a reset form.Ithnan
A
0

My solution is:

$el.off('select2:unselect')
$el.on('select2:unselect', function (event) {
    var $option = $('<option value="" selected></option>');
    var $selected = $(event.target);

    $selected.find('option:selected')
             .remove()
             .end()
             .append($option)
             .trigger('change');
    });
Amadeus answered 4/9, 2017 at 16:15 Comment(0)
C
0

I dont know if anyone else experienced this, but once the code hit the trigger('change') my javascript just stopped, never returned form the trigger, and the rest of the function was never executed.

I am not familiar enough with jquerys trigger to say that this is expected on not. I got around it by wrapping it in a setTimeout, ugly but effective.

Chantellechanter answered 8/10, 2018 at 0:18 Comment(0)
T
0
<label for="RECEIVED_BY" class="control-label"> Received into store By </label>
<label class="pull-right">
  <button
    type="button"
    title="Clear Received into store By"
    class="receive_clear clear-button"
    aria-label="Select2 options"
  >
    x
  </button></label
>
<select type="text" class="clear_receive_info_by">
  <option value="">--Select--</option>
  <option value="value1">value1</option>
  <option value="value2">value2</option>
  <option value="value3">value3</option>
</select>

jQuery:

var $clear_receive_info_by = $(".clear_receive_info_by").select2();
$(".receive_clear").on("click", function () {
    $clear_receive_info_by.val(null).trigger("change");
});
Treasonable answered 9/12, 2020 at 6:37 Comment(0)
S
0

I've read all the answers and many have been deprecated.

This is how currently you can clear and set the place holder value:

// Clear and put a blank select placeholder
$("#MySelect").prop('disabled', false).find("option:gt(0)").remove();
Schreib answered 22/1, 2021 at 17:52 Comment(0)
C
0

this worked for me using select2 version Select2 4.0.5 $('.classToClear').select2().val('');

Cognition answered 13/11, 2021 at 11:12 Comment(0)
L
0
$('#select_id').select2('data', null);

will reset the select2 and show the placeholder

Leatherwood answered 26/10, 2022 at 0:59 Comment(0)
A
0

Ok, so the actual solution (for a common case where you have a "chose item" disabled and selected first item), is very simple, actually:

$("select.select2").trigger("reset").trigger("change")
Accoutre answered 27/11, 2022 at 2:31 Comment(0)
P
-2

I do this for this case:

  $('#select').val('');
  $('.select2.select2-container').remove();
  $('.select2').select2();
  1. I change the select value into empty
  2. I remove container for select2
  3. Re-call select2
Poetize answered 16/1, 2019 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.