In my select2 select, i need to append li after document is ready, and after appending, how can i reinitialize select2. If I once close and again open the select, the appended data are selectable but not as soon as i append. How can i reinitialize it.
Select2 Initialize select after appending data to existing select
Asked Answered
You have to destroy the select2 on these elements and then reinitialize it.
$("select").select2("destroy").select2();
thanks, it did the magic and i added $("select").select2("open"); to reopen it. –
Spa
I'm getting an error: The select2('destroy') method was called on an element that is not using Select2. –
Weatherford
@Weatherford that means the elements you select haven't been initialized by select2 using
.select2()
. –
Quit I have like 5 dropdowns well initialized! even tried to target 1 , but still getting the same error –
Weatherford
Then its hard to see the cause of this without code. Best will be to create a new question for this with code samples so we can see it. –
Quit
Very useful when using a select2 in a modal –
Behold
Thanks to @Mivaweb for answer above ^
So if I use:
$("select").select2("destroy").select2();
then I'm getting following issue as some guys in comments on answer above:
The select2('destroy') method was called on an element that is not using Select2
But it does not mean that it is not working, it works, but need to update approach a bit.
Working solution for me:
STEP1: destroy existing select2 instances
STEP2: update options or select
STEP3: and now init new select2 instances
For example:
$(".select2me-filter").select2("destroy");
... Here do option updates you need
$(".select2me-filter").select2();
A little addition to @Mivaweb's answer. If you get the error message "The select2('destroy') method was called on an element that is not using Select2", then you can do the following:
if ($("select").hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
$("select").select2("destroy");
}
And then you can reinitialize: $("select").select2();
© 2022 - 2024 — McMap. All rights reserved.