Dracke
Dracke

Reputation: 651

Clear multiple select jquery-select2

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/

Upvotes: 8

Views: 24260

Answers (5)

AntonK
AntonK

Reputation: 2320

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

Upvotes: 0

Murtaza Mehmudji
Murtaza Mehmudji

Reputation: 319

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

$("#workload-selector").val([]).change();

Upvotes: 19

Alex Z
Alex Z

Reputation: 113

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

Upvotes: 0

RicardoPHP
RicardoPHP

Reputation: 574

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

$("#reset").click(function(){
  $("#workload-selector").val(null).trigger('change');
});

Upvotes: 4

xjmdoo
xjmdoo

Reputation: 1736

You can just do:

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

Also according to the docs this also works:

$("#workload-selector").val("");
$("#workload-selector").trigger("change");

Upvotes: 7

Related Questions