How to remove select2 from dom
Asked Answered
M

4

58

Say we have a simple select2 list:

<select id="e1">
  <option value="AL">Alabama</option>
    ...
  <option value="WY">Wyoming</option>
</select>

Initiated like:

$("#e1").select2();

How can I remove select2 and return it to a regular dropdown? I can't find any examples or entry in documentation.

Something like:

$("#e1").select2('remove'); 

would be nice.

Monotonous answered 11/10, 2013 at 22:30 Comment(3)
Link to docs: select2.org/programmatic-control/methods#event-unbindingPrimal
Should be $('#elm').select2( 'destroy' ); ReferenceCapstan
Selectize is better than select2 selectize.github.io/selectize.js i recommend it.Theoretics
G
130

You need to use destroy method on select2. See the Documentation

i.e

 $("#e1").select2('destroy'); 
Guaranty answered 11/10, 2013 at 22:32 Comment(1)
Link has changed (they replaced it with docs for 4.0 which are currently woefully incomplete). Passing explanation can be found here: select2.github.io/select2/#lifecycleTenatenable
D
15

That work for me!

var $select = $('.select2').select2();
//console.log($select);
$select.each(function(i,item){
  //console.log(item);
  $(item).select2("destroy");
});
Deformed answered 13/2, 2015 at 19:5 Comment(3)
Worked for me, to destroy every select2 instanceChiapas
Important thing is that if you want to destroy select2 then make sure you have added it first, if your select input is not has select2 then destroy will not work.Goodwill
@Goodwill There is a pretty nice tweak for this: https://mcmap.net/q/331572/-how-to-handle-quot-the-select2-39-destroy-39-method-was-called-on-an-element-that-is-not-using-select2-quot. Btw you dont need the each loop, works without it.Fireguard
T
5

Version 4.0

$element.data('select2').destroy();
Tacnaarica answered 25/8, 2017 at 6:8 Comment(0)
P
1
$(".select2").select2('destroy');
$(".select2").val('Your Value');
$('.select2').each(function () {
    $(this).select2({ dropdownParent: $(this).parent() });
});
Preferable answered 6/2, 2021 at 13:18 Comment(1)
While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained.Boatman

© 2022 - 2024 — McMap. All rights reserved.