Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset select2 value and show placeholder

People also ask

How do I reset Select2?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();

How do I set Select2 values?

To set selected value of jQuery Select2 with JavaScript, we call val and then trigger . Then we set its value with val to the option with value 0. Finally, we call trigger with 'change' to update the drop down to show the value we set.

How do I hide Select2 search box?

In order to hide the search box in select2, you can hide the search box by setting "minimumResultsForSearch" to a negative value. $('select'). select2({ minimumResultsForSearch: -1 });


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

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

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

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


With Select2 version 4.0.9 this works for me:

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

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.