Prasad Patel
Prasad Patel

Reputation: 747

How to clear select2 dropdown?

I am working on a requirement that I have to clear a select2 dropdown box after form submission through ajax. I have searched & tried few solutions but didn't work though.

my select2 code is:

$(document).ready(function(){
 $("#my_select_id").select2({
      placeholder: "Select One Option",
      allowClear: true,
      initSelection: function(element, callback) { }
 }); 
})

Script to clear select2 is:

$('#my_select_id').select2("val", "");

Could anyone please tell what's wrong in this code, Thanks.

Upvotes: 8

Views: 21835

Answers (7)

Misael C. Homem
Misael C. Homem

Reputation: 121

2024

Just for those who are looking for it (like I needed to), but to clear the selection of a select2 component, according to the documentation at https://select2.org/programmatic-control/add-select-clear-items, just do:

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

Upvotes: 0

SAHIL SRIVASTAVA
SAHIL SRIVASTAVA

Reputation: 111

In case Leo's answer here does not helps, please try the below - it worked for me:

$('#your_select_input').val([]).trigger('change');

Upvotes: 0

Anjani Barnwal
Anjani Barnwal

Reputation: 1522

try this $('#select_id').empty();

Upvotes: 0

Will Paiz
Will Paiz

Reputation: 75

Try this:

var newOption = new Option("", 0, false, false);
$('#your-dropdown').append(newOption).trigger('change');

Upvotes: 0

jfeid
jfeid

Reputation: 71

Because nothing of the available options worked for me (even the official example https://select2.org/programmatic-control/add-select-clear-items#clearing-selections)

I finally managed to clear the selections as follows:

$('select.select2 option:selected').attr('selected', false).attr('data-select2-id', false);
$('select.select2').val('').trigger('change');

Hope it helps

Upvotes: 0

AdamIJK
AdamIJK

Reputation: 655

Try the following code instead of val use data it will work

$("#my_select_id").select2('data', null)

Upvotes: 2

Leo Schoberwalter
Leo Schoberwalter

Reputation: 166

Try this: $('#your_select_input').val('').trigger('change');

Upvotes: 15

Related Questions