Question

I'm using select2 plugin for dropdown menus in a rails application. However if i'm rendering a form with a JS call to server select2 is not applied to the inputs.

Here is a js.erb file describing what I mean

$("#container").html("<%= j render partial: 'form' %>");
$(".select-list").select2()

I've tried setting the context with:

$(".select-list", document).select2()

But that doesn't work either. How can I apply select2 to my inputs after a server responds to a JS call?

Was it helpful?

Solution

Since you are replacing the content of the #container you need to bind the select2 or any other events for that matter with the jQuery on method (http://api.jquery.com/on/).

So doing the following should solve your issue:

On your js.erb:

$("#container").html("<%= j render partial: 'form' %>").trigger('show');

Then on your assets/javascripts/somefile.js.erb, as long as somefile.js.erb is included in your application.js, or you could even place the following at the bottom of your application.js:

$('#container').on('show', function() {
    $('.select-list').select2();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top