Clear multiple select jquery-select2

14,258

Solution 1

You can just do:

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

Also according to the docs this also works:

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

Solution 2

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

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

Solution 3

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

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

Related videos on Youtube

Dracke
Author by

Dracke

Apparently, this user prefers to keep an air of mystery about them. Or does he?

Updated on June 04, 2022

Comments

  • Dracke
    Dracke almost 2 years

    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/

  • Piotrek Zatorski
    Piotrek Zatorski about 5 years
    Does not work for multiple select. It makes one empty tag.
  • RicardoPHP
    RicardoPHP almost 5 years
    here docs about clearing select2 values, it doesnt matter if multiple or single ... select2.org/programmatic-control/…
  • GhostBytes
    GhostBytes over 3 years
    This is the only answer that actually works for multi select.
  • Yagnesh bhalala
    Yagnesh bhalala over 2 years
    Nice answers dude, I'm thanks full for you. :)