I am using bootstrap's remote-modal feature, that is bringing the modal content using ajax
I'm assuming by this that you are referring to the remote
option, which loads the content once, and happens to actually be deprecated.
the problem is that sometimes (often the first time I load the modal) the select2 styles are loaded and then removed
By this I'm assuming you mean that the <select>
is given the Select2 theme, and then it reverts back to a standard <select>
. Almost as though Select2 was never initialized, or .select2('destroy')
was called on it.
It's important to note that the reason why this probably only happens on the first time is because (as marked above), the modal content is only loaded once. So when the shown
event is triggered any time after that, the <select>
already exists and Select2 will be able to be initialized right away. And there isn't a risk of the modal content being reloaded or anything, which could be an issue.
With that in mind, the remote
option for Bootstrap modals just calls $modalBody.load()
when the modal is initialized with the remote url, which will load the remote content into the modal. It triggers the loaded
event after the loading completes, which is where you actually want to be initializing Select2.
The shown
method triggered by Bootstrap actually doesn't wait for the remote data to finish loading, so it's possible that the shown
method will finish before the modal data is loaded in. This race condition has the very real possibility of causing issues like this, where Select2 is initialized on an element that ends up being replaced.
Now, this mean you should only need to make one change in your code: change the shown
event to loaded
.