[javascript] Resetting Select2 value in dropdown with reset button

What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.

So when I press my button I want "All" to be shown again.

jQuery

$("#d").select2();

html

<select id="d" name="d">
  <option selected disabled>All</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

This question is related to javascript html forms jquery-select2

The answer is


    // Store default values
    $('#filter_form [data-plugin="select2"]').each(function(i, el){
        $(el).data("seldefault", $(el).find(":selected").val());
        });

    // Reset button action
    $('#formresetbtn').on('click', function() {
        $('#filter_form [data-plugin="select2"]').each(function(i, el){
            $(el).val($(el).data("seldefault")).trigger('change');
            });
        });

The best way of doing it is:

$('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
$('#e1').append(new Option()); // to add the placeholder and the allow clear

Sometimes I want to reset Select2 but I can't without change() method. So my solution is :

function resetSelect2Wrapper(el, value){
    $(el).val(value);
    $(el).select2({
        minimumResultsForSearch: -1,
        language: "fr"
    });
}

Using :

resetSelect2Wrapper("#mySelectId", "myValue");

To achieve a generic solution, why not do this:

$(':reset').live('click', function(){
    var $r = $(this);
    setTimeout(function(){ 
        $r.closest('form').find('.select2-offscreen').trigger('change'); 
    }, 10);
});

This way: You'll not have to make a new logic for each select2 on your application.

And, you don't have to know the default value (which, by the way, does not have to be "" or even the first option)

Finally, setting the value to :selected would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select is to return input element values to the server-sent ones.

EDIT: Alternatively, considering the deprecated status of live, we could replace the first line with this:

$('form:has(:reset)').on('click', ':reset', function(){

or better still:

$('form:has(:reset)').on('reset', function(){

PS: I personally feel that resetting on reset, as well as triggering blur and focus events attached to the original select, are some of the most conspicuous "missing" features in select2!


you can used:

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

It's very simple and work right! If use with reset button:

$('#btnReset').click(function() {
    $("#d").val(null).trigger("change"); 
});

to remove all option value

$("#id").empty();

What I found works well is as follows:

if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use

$('#id').select2('val',0);

0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.

If you don't have a placeholder and just want no text to appear in the field use:

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

According to the latest version (select2 3.4.5) documented here, it would be as simple as:

 $("#my_select").select2("val", "");

You can also reset select2 value using

$(function() {
  $('#d').select2('data', null)
})

alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.


Just to that :)

$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
  $(this).change();
});

For me it works only with any of these solutions

$(this).select2('val', null);

or

$(this).select2('val', '');

version 4.0

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

This is the correct solution from now on according to deprecated message thrown in debug mode: "The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"


If you have a populated select widget, for example:

<select>
    <option value="1">one</option>
    <option value="2" selected="selected">two</option>
    <option value="3">three</option>
    ...

you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:

$('button[type="reset"]').click(function(event) {
    // Make sure we reset the native form first
    event.preventDefault();
    $(this).closest('form').get(0).reset();
    // And then update select2 to match
    $('#d').select2('val', $('#d').find(':selected').val());
}

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.


I see three issues:

  1. The display of the Select2 control is not refreshed when its value is changed due to a form reset.
  2. The "All" option does not have a value attribute.
  3. The "All" option is disabled.

First, I recommend that you use the setTimeout function to ensure that code is executed after the form reset is complete.

You could execute code when the button is clicked:

$('#searchclear').click(function() {
    setTimeout(function() {
        // Code goes here.
    }, 0);
});

Or when the form is reset:

$('form').on('reset', function() {
    setTimeout(function() {
        // Code goes here.
    }, 0);
});

As for what code to use:

Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:

$("#d").select2('val', 'All');

If the attribute value="" were to be added to the "All" option, then you could use the code given by Daniel Dener:

$("#d").select2('val', '');

If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:

$('#d').change();

Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:

$('#d').select2('data', null)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?