Reset select2 value and show placeholder

JqueryTwitter BootstrapJquery Select2

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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')

Solution 3 - Jquery

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([]);

Solution 4 - Jquery

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

Solution 5 - Jquery

With Select2 version 4.0.9 this works for me:

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

Solution 6 - Jquery

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.

Solution 7 - Jquery

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

Solution 8 - Jquery

Use this :

$('.select').val([]).trigger('change');

Solution 9 - Jquery

TO REMOVE SELECTED VALUE

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

TO CLEAR OPTION VALUES

$('#employee_id').html('');

Solution 10 - Jquery

This is the correct way:

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

I am using the latest release of Select2.

Solution 11 - Jquery

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

Solution 12 - Jquery

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

Solution 13 - Jquery

You can clear te selection by

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

But it wont turn you back to your placeholder.

So its a half solution

Solution 14 - Jquery

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

Solution 15 - Jquery

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

Solution 16 - Jquery

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([]);
 });

Solution 17 - Jquery

For the place holder

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

To reset a select 2

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

Hope this helps

Solution 18 - Jquery

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>

Solution 19 - Jquery

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

Solution 20 - Jquery

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.

Solution 21 - Jquery

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.)

Solution 22 - Jquery

Use this code into your js file

$('#id').val('1');
$('#id').trigger('change');

Solution 23 - Jquery

From select2 website,

$("#mySelect2ControlId").val(null).trigger("change");

Solution 24 - Jquery

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

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

Solution 25 - Jquery

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.

Solution 26 - Jquery

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

Solution 27 - Jquery

Using select2 version 3.2 this worked for me:

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

Didn't need to implement initSelection

Solution 28 - Jquery

$('myselectdropdown').select2('val', '0')

where 0 is your first value of the dropdown

Solution 29 - Jquery

This solution work for me (Select2 4.0.13)

$('#select').on("select2:unselecting", function (e) {
   $(this).val('').trigger('change');
   e.preventDefault();
});

Solution 30 - Jquery

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.

Solution 31 - Jquery

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

Solution 32 - Jquery

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

Solution 33 - Jquery

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

Solution 34 - Jquery

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

Solution 35 - Jquery

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.

Solution 36 - Jquery

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

Solution 37 - Jquery

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

Solution 38 - Jquery

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

Solution 39 - Jquery

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

Solution 40 - Jquery

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

Solution 41 - Jquery

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.

Solution 42 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfefeView Question on Stackoverflow
Solution 1 - JqueryAbdelMalekView Answer on Stackoverflow
Solution 2 - JqueryNorthCatView Answer on Stackoverflow
Solution 3 - Jqueryuser764357View Answer on Stackoverflow
Solution 4 - JqueryM.TaeView Answer on Stackoverflow
Solution 5 - JqueryIlludiumPu36View Answer on Stackoverflow
Solution 6 - JqueryMarcio MazzucatoView Answer on Stackoverflow
Solution 7 - JquerySeanView Answer on Stackoverflow
Solution 8 - JquerySachin GendView Answer on Stackoverflow
Solution 9 - JqueryShanka SMSView Answer on Stackoverflow
Solution 10 - JqueryTreeZView Answer on Stackoverflow
Solution 11 - JqueryZabith RafeekView Answer on Stackoverflow
Solution 12 - Jquerytech_boyView Answer on Stackoverflow
Solution 13 - JqueryRodrigo ButtaView Answer on Stackoverflow
Solution 14 - JqueryMahmut AydınView Answer on Stackoverflow
Solution 15 - JqueryChad KuehnView Answer on Stackoverflow
Solution 16 - JqueryAlisha LamichhaneView Answer on Stackoverflow
Solution 17 - JqueryRinto GeorgeView Answer on Stackoverflow
Solution 18 - JqueryfmsfView Answer on Stackoverflow
Solution 19 - JqueryAbaView Answer on Stackoverflow
Solution 20 - JquerymangonightsView Answer on Stackoverflow
Solution 21 - Jqueryguero64View Answer on Stackoverflow
Solution 22 - JqueryNhoufyView Answer on Stackoverflow
Solution 23 - JqueryProgramnikView Answer on Stackoverflow
Solution 24 - JqueryИгорь ХлебниковView Answer on Stackoverflow
Solution 25 - JqueryAkhilesh BalachandderView Answer on Stackoverflow
Solution 26 - JqueryCanser YanbakanView Answer on Stackoverflow
Solution 27 - JqueryshakView Answer on Stackoverflow
Solution 28 - JqueryMomaad Jamshed AlamView Answer on Stackoverflow
Solution 29 - JqueryAndrea FiniView Answer on Stackoverflow
Solution 30 - Jqueryuser2243380View Answer on Stackoverflow
Solution 31 - JqueryAndrew NarteyView Answer on Stackoverflow
Solution 32 - JqueryEllery NewcomerView Answer on Stackoverflow
Solution 33 - JqueryMaxView Answer on Stackoverflow
Solution 34 - JqueryDaniel OrtegónView Answer on Stackoverflow
Solution 35 - JqueryTexasNeoView Answer on Stackoverflow
Solution 36 - JquerydavidView Answer on Stackoverflow
Solution 37 - JqueryMohammad Ali AbdullahView Answer on Stackoverflow
Solution 38 - JqueryMauricio SolórzanoView Answer on Stackoverflow
Solution 39 - Jqueryejay56View Answer on Stackoverflow
Solution 40 - JqueryVicky PView Answer on Stackoverflow
Solution 41 - JqueryYasser CHENIKView Answer on Stackoverflow
Solution 42 - JqueryScrambleView Answer on Stackoverflow