I’m using select2 on a form. But want to use it throughout the application.
I have this part in my application.html.erb
<script type="text/javascript">
$(document).ready(function() {
<%= yield :document_ready %>
});
</script>
And this in my view:
<% content_for :document_ready do %>
$("#menu_category_id").select2({minimumResultsForSearch: 10});
<% end %>
and this is the actual input in the view:
<%= f.input :menu_category_id, :collection => @product.menu.menu_categories,
:label_method => :name, :value_method => :id, :label => "Category" %>
This works without any problems. However I don’t want to repeat this in all the views and would like to handle that with simple_view.
Best would be that if I use:
<%= f.input :menu_category_id, :collection => @product.menu.menu_categories,
:label_method => :name, :value_method => :id, :label => "Category",
:select2 => 'minimumResultsForSearch: 10' %>
it would automatically put it in the :document_ready part. So if there are 3 selects on a page it would do it for all of them with all the options that are specified in :select2
Is this possible with custom inputs? Or any other way?
I don’t think you need a custom input or the content_for helpers here. Assign a CSS class to the inputs you want
select2for, saywith_select2. Next, assign them a data attribute specifying theminimumResultsForSearchvalue, saydata-minimum-results. Ondocument.readythen loop through all the inputs with classwith_select2and callselect2on them with theminimumResultsForSearchfrom the data attribute.