Clear multiple select jquery-select2
Asked Answered
I

5

8

I am trying to create a reset button for jquery-select2 multiple select. I have no idea why my solution doesn't work.

Html:

<select id="workload-selector" class="js-source-states-2" multiple="multiple" style="width: 100%">             
  <option value="haha">haha</option>
  <option value="haha2">haha2</option>
  <option value="haha3">haha3</option>
</select>

<button id="reset">
Reset
</button>

Javascript:

$("#workload-selector").select2();
$("#reset").click(function(){
  $("#workload-selector option:selected").removeAttr("selected");
});

I made it on jsFiddle: https://jsfiddle.net/DTcHh/41975/

Incise answered 23/1, 2018 at 11:24 Comment(1)
possible duplicate #15205762Herakleion
P
8

You can just do:

$("#workload-selector").select2('val', '');

Also according to the docs this also works:

$("#workload-selector").val("");
$("#workload-selector").trigger("change");
Plunk answered 23/1, 2018 at 11:29 Comment(1)
Does not work for multiple select. It makes one empty tag.Lanchow
R
18

The select2 multiple saves value in an array All you need to do is

$("#workload-selector").val([]).change();
Roa answered 14/10, 2019 at 10:21 Comment(1)
This is the only answer that actually works for multi select.Quillen
P
8

You can just do:

$("#workload-selector").select2('val', '');

Also according to the docs this also works:

$("#workload-selector").val("");
$("#workload-selector").trigger("change");
Plunk answered 23/1, 2018 at 11:29 Comment(1)
Does not work for multiple select. It makes one empty tag.Lanchow
M
4

I have done just that, there it goes a sample of my elaboration

$("#reset").click(function(){
  $("#workload-selector").val(null).trigger('change');
});
Manicurist answered 29/5, 2019 at 17:3 Comment(2)
here docs about clearing select2 values, it doesnt matter if multiple or single ... select2.org/programmatic-control/…Manicurist
Nice answers dude, I'm thanks full for you. :)Atonal
A
0

In the documentation https://select2.org/programmatic-control/add-select-clear-items#clearing-selections saying that I need set null value. When select have multiple choices, it gave me a blank selected option. But if set not exist value, it clear normally for me.

For example: if in options u have:

<select id="mySelect2" multiple="multiple">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

This normally clear select.

$('#mySelect2').val(-100).trigger('change');
Analyst answered 4/9, 2019 at 8:50 Comment(0)
P
0

This works for but single and multi and is according to docs https://select2.org/programmatic-control/add-select-clear-items#clearing-selections

$('#mySelect2').val(null).trigger('change');
Pistoia answered 26/8, 2022 at 1:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.