How to clean completely select2 control?
Asked Answered
D

11

58

I'm working with the awesome select2 control.

I'm trying to clean and disable the select2 with the content too so I do this:

$("#select2id").empty();
$("#select2id").select2("disable");

Ok, it works, but if i had a value selected all the items are removed, the control is disabled, but the selected value is still displayed. I want to clear all content so the placeholder would be showed. Here is a example I did where you can see the issue: http://jsfiddle.net/BSEXM/

HTML:

<select id="sel" data-placeholder="This is my placeholder">
    <option></option>
    <option value="a">hello</option>
    <option value="b">all</option>
    <option value="c">stack</option>
    <option value="c">overflow</option>
</select>
<br>
<button id="pres">Disable and clear</button>
<button id="ena">Enable</button>

Code:

$(document).ready(function () {
    $("#sel").select2();

    $("#pres").click(function () {
        $("#sel").empty();
        $("#sel").select2("disable");
    });

    $("#ena").click(function () {
        $("#sel").select2("enable");
    });
});

CSS:

#sel {
    margin: 20px;
}

Do you have any idea or advice to this?

Deraign answered 30/4, 2013 at 23:31 Comment(1)
Title is missleading. Please change for future readers.Culture
G
29

Why all this trouble???

use:

 $('#sel').select2('data', null);
Grosberg answered 23/10, 2013 at 15:50 Comment(4)
This method has been deprecated and will be removed in Select2 4.1Monosepalous
Worked Perfectly! You are my angle!Megadeath
it doesn't work with new implementations of select2. The answer of Sarath Kumar it's now the working one.Examinant
what I will do if I have to keep selected option only and delete remaining all?Unaccountedfor
H
111

Whenever you alter or change a value in select2 try to use the trigger ("change"):

$('#sel').empty().trigger("change");
Hortative answered 7/2, 2017 at 19:32 Comment(3)
Using empty() rather than value(null) worked for me on Select2 4.0.3, thanks!Cholecystectomy
fyi: this also removes the placeholderMortise
Worked like a charm. \Outgrow
M
36

Try this from official select2 documentations.

version 4

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

For version 3.5.3

$("#sel").select2("val", "");
Monosepalous answered 12/11, 2016 at 19:16 Comment(4)
OMG, this is it! None of the above worked for me. I guess, this solution is for Select2 v4Vachill
This did not work for me. It looks like all it changed was the size of the select box. It is now super narrow (one character wide)Suffice
@Suffice please check your select2 version.Monosepalous
Just to follow up. I tried it again, without editing any code, and it worked. Weird, but I'll take what I can get. Also, the docs even say to do this, so it must've been some sort of misfire :)Suffice
G
29

Why all this trouble???

use:

 $('#sel').select2('data', null);
Grosberg answered 23/10, 2013 at 15:50 Comment(4)
This method has been deprecated and will be removed in Select2 4.1Monosepalous
Worked Perfectly! You are my angle!Megadeath
it doesn't work with new implementations of select2. The answer of Sarath Kumar it's now the working one.Examinant
what I will do if I have to keep selected option only and delete remaining all?Unaccountedfor
G
16

To clean completely a select2 (>= v4) component:

$('#sel').val(null).empty().select2('destroy')
  • val(null) -> remove select form data
  • empty -> remove select options
  • select2(destroy) -> remove select2 plugin

Then you can create a new select2 component with the same select HTML node if you want.

Galvano answered 13/4, 2019 at 19:53 Comment(0)
V
10

I'm using Select2 v4.0 (4.0.6-rc.0)

Using the following clears all of the values in the dropdown field:

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

Doing this removes them entirely and they cannot be re-selected until the page refreshes.

If all you want to do is remove the selection, do the following:

$('#id_of_select2_select').val(null).trigger('change');

The currently selected options are cleared and the user will be able to re-select their intended options.

Vertu answered 12/12, 2018 at 14:58 Comment(1)
val(null).trigger('change') is the way... you save my lifePeradventure
R
2

As answered Sarath Kumar:

$('#sel').val(null).trigger('change');

Reference from the official documentation, here is the link:

https://select2.org/programmatic-control/add-select-clear-items#clearing-selections

Roselane answered 29/11, 2017 at 11:59 Comment(2)
I'm not sure how much value is gained from this duplicate answer.Piggyback
Just added the missing reference to the official documentation. Thanks for feedback.Roselane
P
1

Try this:- http://jsfiddle.net/GqbSN/

  $(document).ready(function () {
    $("#sel").select2();

    $("#pres").click(function () {
      $('#s2id_sel > a > span').text($(sel).data('placeholder')); 
        //$('.select2-container > a > span').text('This is my placeholder');
        $("#sel").select2("disable");;
       });

    $("#ena").click(function () {
        $("#sel").select2("enable");
    });
});

Note

$('#s2id_sel > a > span').text($(sel).data('placeholder')); What i understand looking at this plugin is the markup it creates from the select that we provide it generates id as #s2id_ + "yourselectelementid". So this would be a better way to use it in case you have multiple select controls and you want to disable only the some or one of them.

If you want to clear the select contents:- http://jsfiddle.net/G7TXj/

Platter answered 30/4, 2013 at 23:39 Comment(5)
It should work except, you need to remove this line $("#sel").empty();Recrystallize
I have put both the versions now.. Probably by clear he meant clear the selection. Thanks for pointing that out.. :)Platter
Really thanks both! yes, i want to clear the contents too, sorry if i was not specific...Deraign
@Joëlle Please see my update and see if it makes sense in your case.Platter
Ok, thats it! thanks again. By the by, could you put me a little example doing the same but deleting three select2 at the same time using its id.Deraign
K
1

I tested this code and got the answer:

$('#sel').val(null).empty().select2();
Kaycekaycee answered 24/5, 2022 at 7:58 Comment(0)
G
0

My select2 in first option to "all". This option clears the other options and the first option is selected

var $eventSelect = $("#storeList");
   $("#storeList").on("change", function (e) {
        if (e.added != undefined) {
            if (e.added.id == 0 && e.val.length>1) {
                   removeTags();
                $("#storeList").val('0').select2();

            }

        }

    });

  function removeTags(){
        $eventSelect.select2('data', null);

    }
Glacial answered 15/6, 2017 at 9:30 Comment(0)
N
0

As per the doc here, you need to use the code as below

$('#mySelect2').val(null).trigger('change');
Norahnorbert answered 20/2, 2020 at 3:18 Comment(0)
Z
-1

try using this:

$('#sel').html('').select2();
Zante answered 2/3, 2019 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.