Select2 Initialize select after appending data to existing select
Asked Answered
S

3

17

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.

Spa answered 19/12, 2014 at 7:29 Comment(0)
Q
43

You have to destroy the select2 on these elements and then reinitialize it.

$("select").select2("destroy").select2();
Quit answered 19/12, 2014 at 7:37 Comment(6)
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 errorWeatherford
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 modalBehold
C
5

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();
Condemnatory answered 21/11, 2018 at 17:17 Comment(0)
K
0

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();

Kibbutz answered 12/10, 2022 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.