Skip to content

Instantly share code, notes, and snippets.

@kevin-brown
Created May 27, 2015 23:26
Show Gist options
  • Save kevin-brown/cd30a3f67c563f912380 to your computer and use it in GitHub Desktop.
Save kevin-brown/cd30a3f67c563f912380 to your computer and use it in GitHub Desktop.
select2 multiple being 'unformated' after loading

I am using select2 with Twitter Bootstrap and JQuery, I am using bootstrap's remote-modal feature, that is bringing the modal content using ajax, and one of the elements am bringing is a <select multiple>...</select> tag that I want to turn into a select2-multiple. I do it like this:

$(function(){
    $('#modal').on('shown.bs.modal', function(){
        $(this).find('#tags').select2()
    }
})

and it usually works, the problem is that sometimes (often the first time I load the modal) the select2 styles are loaded and then removed, I have already debuged it and I know that's what happens so I'm looking for the culprit

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment