Resetting Select2 value in dropdown with reset button
Asked Answered
W

19

72

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>
Wait answered 4/3, 2013 at 15:39 Comment(3)
Can you should the code that you have for your button as well?Laktasic
<input type="reset" id="searchclear" value="clear">Wait
duplicate post #13240547Afternoons
L
67

I'd try something like this:

$(function(){
    $("#searchclear").click(function(){
        $("#d").select2('val', 'All');
    });
});
Laktasic answered 5/3, 2013 at 13:37 Comment(1)
You can also use something like this ---- $("#d").select2('val', ''); It will also bring the DD value to initial.Knowable
A
63

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.

Ashby answered 19/3, 2013 at 16:49 Comment(2)
I tried this out... and it works, except then nothing is selected. The OP wanted the first option to be selected, so something like $('#d').select2('data', $('#d').find('option')[0]) would reset the select2 value to the first option in the original select element. (@Lenart, plus one for the more generic solution)Magnum
allowClear needs placeholder. If not there will be this error TypeError: this.placeholder is undefinedErnaernald
K
60

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"

Kimmie answered 8/10, 2016 at 23:10 Comment(3)
This needs to be bumped way up! With V4 none of the other solutions work.Levine
this is the only method I have seen work, thank you.Sine
Worked for me for version 4.0.13Nonmoral
R
32

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

 $("#my_select").select2("val", "");
Roving answered 8/1, 2014 at 1:42 Comment(1)
Ultimately, this solution is the only one that worked for me. I had several select2's that I wanted to reset, and using one css selector did not work. I had to loop over them and reset them individually.Polivy
M
21

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"); 
});
Malka answered 26/5, 2015 at 7:0 Comment(2)
Worked for me too, didn't get any of the other solutions to work!Scornful
if you are using jquery validation with required then it will throw validation errorConverse
L
7

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
Lvov answered 31/10, 2013 at 21:40 Comment(2)
this works the best, none of the other solutions helpedWoodborer
You saved my day :)Leffen
E
7

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)
Exogamy answered 8/11, 2014 at 4:47 Comment(2)
$("form").on("reset",... worked for me, in the event handler I simply called $(".select2").trigger("change"); to refresh all of the select2 objects on the page since reset resets the underlying select lists properly. setTimeout() is a nice trick!Rabid
Triggering $('select').change(); on all selects, in the setTimeout called from the form's reset handler $('form').on('reset', ... resolves the problem. This should be the accepted answer.Tighe
A
5

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());
}
Abnegate answered 22/10, 2013 at 10:53 Comment(0)
L
3

Just to that :)

$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
  $(this).change();
});
Laurentian answered 18/2, 2020 at 23:23 Comment(0)
T
2

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','');
Tasman answered 29/8, 2015 at 17:20 Comment(0)
P
1

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!

Pontiff answered 4/5, 2014 at 20:47 Comment(0)
A
0

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.

Arva answered 1/11, 2014 at 15:43 Comment(1)
This one worked for me as I was trying to repopulate the values of drop down and was retaining the last selected optionAbundance
P
0

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");
Palate answered 24/5, 2016 at 9:46 Comment(0)
H
0

For me it works only with any of these solutions

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

or

$(this).select2('val', '');
Hooten answered 13/9, 2016 at 9:25 Comment(0)
S
0
    // 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');
            });
        });
Sculptress answered 6/1, 2018 at 20:28 Comment(0)
H
0

If you want to reset forms in edit pages, you can add this button to forms

<button type="reset" class="btn btn-default" onclick="resetForm()">Reset</button>

and write your JS code like this:

function resetForm() {
    setTimeout(function() {
        $('.js-select2').each(function () {
            $(this).change();
            /* or use two lines below instead */
            // var oldVal = $(this).val();
            // $(this).select2({'val': oldVal});
        });
    }, 100);
}
Hindermost answered 30/6, 2021 at 10:20 Comment(0)
S
0

Lots of great answers, but with the newest version none worked for me. If you want a generic solution for all select2 this is working perfectly.

Version 4.0.13 tested

$(document).ready(function() {
    $('form').on('reset', function(){
        console.log('triggered reset');
        const $r = $(this);
        setTimeout(function(){
            $r.closest('form').find('.select2-hidden-accessible').trigger('change');
        }, 10);
    });
});
Sagesagebrush answered 30/11, 2021 at 12:9 Comment(0)
S
0

$(function(){
    $("#btnReset").click(function(){
        $("#d").select2({
          val: "",
        });
    });
});
Storage answered 8/2, 2023 at 13:22 Comment(0)
B
-2

to remove all option value

$("#id").empty();
Brantbrantford answered 19/11, 2020 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.