fefe
fefe

Reputation: 9065

Reset select2 value and show placeholder

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

Upvotes: 276

Views: 555065

Answers (30)

Showkii Paa
Showkii Paa

Reputation: 101

Problem:

When managing multiple Select2 dropdowns with dependencies within a single form, resetting dropdown selections using

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

Solution:

To reset Select2 dropdown selections effectively while preserving dependencies between multiple dropdowns within a form, a different approach is required. By combining both .val(null) and .trigger('change') with .select2(), you ensure a more reliable and predictable behavior.

$("#customers_select").val(null).select2();

This revised content provides a comprehensive explanation of the problem and offers a clear solution for resetting Select2 dropdowns with dependencies within a form.

Upvotes: 0

Lokendra
Lokendra

Reputation: 56

$(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.

Upvotes: 2

RRE Designs
RRE Designs

Reputation: 425

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

Upvotes: 0

Adrian P.
Adrian P.

Reputation: 5228

$('#select_id').select2('data', null);

will reset the select2 and show the placeholder

Upvotes: 0

Yasser CHENIK
Yasser CHENIK

Reputation: 407

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.

Upvotes: 2

Vicky P
Vicky P

Reputation: 762

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

Upvotes: 2

ejay56
ejay56

Reputation: 41

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

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

Upvotes: 0

Mohammad Ali Abdullah
Mohammad Ali Abdullah

Reputation: 331

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

Upvotes: 0

IlludiumPu36
IlludiumPu36

Reputation: 4304

With Select2 version 4.0.9 this works for me:

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

Upvotes: 46

Andrea Fini
Andrea Fini

Reputation: 64

This solution work for me (Select2 4.0.13)

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

Upvotes: 1

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

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

Upvotes: 2

Programnik
Programnik

Reputation: 1565

From select2 website,

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

Upvotes: 3

david
david

Reputation: 86

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

Upvotes: 1

Alisha Lamichhane
Alisha Lamichhane

Reputation: 514

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

Upvotes: 5

Scramble
Scramble

Reputation: 119

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

Upvotes: -2

TexasNeo
TexasNeo

Reputation: 611

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.

Upvotes: 0

Nhoufy
Nhoufy

Reputation: 53

Use this code into your js file

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

Upvotes: 2

M.Tae
M.Tae

Reputation: 1467

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

Upvotes: 68

TreeZ
TreeZ

Reputation: 147

This is the correct way:

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

I am using the latest release of Select2.

Upvotes: 9

Duke
Duke

Reputation: 37060

For the place holder

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

To reset a select 2

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

Hope this helps

Upvotes: 3

Momaad Jamshed Alam
Momaad Jamshed Alam

Reputation: 31

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

where 0 is your first value of the dropdown

Upvotes: 1

Rodrigo Butta
Rodrigo Butta

Reputation: 409

You can clear te selection by

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

But it wont turn you back to your placeholder.

So its a half solution

Upvotes: 6

Sachin Gend
Sachin Gend

Reputation: 171

Use this :

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

Upvotes: 17

Daniel Orteg&#243;n
Daniel Orteg&#243;n

Reputation: 315

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

Upvotes: 0

Zabith Rafeek
Zabith Rafeek

Reputation: 79

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

Upvotes: 8

m00seDrip
m00seDrip

Reputation: 4021

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

Upvotes: 5

guero64
guero64

Reputation: 1049

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

Upvotes: 2

Mahmut Aydın
Mahmut Aydın

Reputation: 869

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

Upvotes: 6

mangonights
mangonights

Reputation: 989

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.

Upvotes: 3

Related Questions