Reputation: 739
I'm using the jQuery select2 plugin in my Rails4 app.
The plugin is working for me in forms that are not using ajax. But, for ajax forms I don't know how to do it.
There's a form inside a bootstrap 3 modal, here's how I load the same:
<%= link_to t(:new), new_address_path, remote: true, :class => 'btn btn-info' %>
$('<%= j render "form", title: "#{t(:address)}" %>').modal();
How can I initialise the select2 plugin for the selects inside this form?
Upvotes: 0
Views: 411
Reputation: 9496
You would do this using javascript
:
// On document ready
$(function(){
$(document).bind('ajaxComplete', function() {
// Activate select2 after ajax request
activateJSPlugins();
});
activateJSPlugins();
});
function activateJSPlugins() {
// Find all dropdowns and initialize select2
$(".controls select").each(function() {
// Initialize select2
$(this).select2();
});
}
$(".controls select")
would be the css
selector you apply to find your select2 controls.
EDIT
/app/assets/javascripts/bootstrap_and_overrides.js
Create a bootstrap_and_overrides.js
file.
/app/assets/javascripts/application.js
//= require bootstrap_and_overrides
Then this code will run for all your selec2 inputs
Upvotes: 0
Reputation: 46
Did I understand it correctly? The form is a modal which is not displayed on the page at first but after some user interactions. In that case the on document ready will not find the element to activate select2. I would suggest to either use the livequery plugin which observes DOM changes, e.g.
$('form.modal').livequery('.controls select',
function(elem){
$(elem).select2();
})
Or you can also put what @Willem suggested into a javascript tag in the html partial of the form modal.
Upvotes: 1