How to clear select2 dropdown?
Asked Answered
D

7

8

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.

Diggins answered 22/3, 2017 at 12:6 Comment(2)
See https://mcmap.net/q/1323999/-listbox-items-remains-after-replace-by-empty-array-in-jqueryTestis
#13240547Baerl
R
15

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

Rockbottom answered 22/3, 2017 at 12:13 Comment(0)
E
2

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

$("#my_select_id").select2('data', null)
Excelsior answered 22/3, 2017 at 12:27 Comment(1)
First, thanks for you reply. I tried that too but didn't work though.Diggins
E
0

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

Eucharis answered 4/10, 2018 at 14:54 Comment(0)
S
0

Try this:

var newOption = new Option("", 0, false, false);
$('#your-dropdown').append(newOption).trigger('change');
Subterranean answered 12/6, 2019 at 19:47 Comment(0)
D
0

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

Divagate answered 22/11, 2021 at 12:57 Comment(0)
M
0

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

$('#your_select_input').val([]).trigger('change');
Mush answered 27/7, 2022 at 6:58 Comment(0)
Q
0

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');
Quadriceps answered 13/9 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.