javascriptjqueryruby-on-railsturbolinksselect2-rails

Select2 is not applied to select element in rails, where do I find the missing link?


Pages that helped me so far:

Expected outcome:

Actual outcome:

Steps I've taken so far:

  1. add it to gem, do bundle install.
  2. add //= require select2 like this

:

//= require jquery
//= require jquery_ujs
//= require bootstrap/modal
//= require turbolinks
//= require select2
//= require_tree .

  1. added the require select2 and require select2-bootstrap to application.css

:

*= require select2
 *= require select2-bootstrap
 *= require_tree .
 *= require_self
 */
  1. in my name.html.erb there is:

:

<%= f.label :tag_list, "Topics" %>
<%= f.select(:tag_list, Tag.all.order(:name).collect { |a| a.name }, {}, id: "tag_list1", label:'Tags', :multiple => true)%>

I've created a Tag.rb (data gets saved to the db): class Tag < ApplicationRecord validates_presence_of :name end

  1. now the final step (from what I understand), I apply the functionality to the element (adding the code to application.js below the //= require_tree .): $( "#dropdown" ).select2({ theme: "bootstrap" });

changed this to:

$( "#tag_list1" ).select2({ theme: "bootstrap" });

Console: Uncaught TypeError: $(...).select2 is not a function

I solve this with:

(function($){
  $(document).on('ready', function(){
      $("#tag_list1").select2({
        theme: "bootstrap",
        tags: true
      });
  });
}(jQuery));

Expected outcome:

Actual outcome:

Please advise.


Update 1 This is the html output:

<input name="item[tag_list][]" type="hidden" value="">
<select id="tag_list1" label="Tags" multiple="multiple" name="item[tag_list][]">
  <option value="12">dev tool</option>
</select>

Solution

  • Looking at the DOM. You should see the following order of loading: jQuery, select2 and then your js files. ( source: https://stackoverflow.com/a/42671121/6430382 )

    Instead of ready add turbolinks:load

    Make a file called /assets/javascripts/select2.js:

    //= require select2-full
    
    $(document).on('turbolinks:load', function(){
      $("#tag_list1").select2({
        theme: "bootstrap",
        tags: true,
        placeholder: "Max 5 topics"
      });
    });
    

    Expected outcome: you get select2 added to your element with all functionality.