Select2-rails gem not working on Rails4

I tried this documentation for select2-rails pearls but an error still appears in my browser console.

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

I am using rails 4.0.1 & select2-rails 3.5.9.3

My application.js

 //= require jquery //= require select2 //= require jquery.ui.accordion //= require jquery.ui.menu //= require jquery.ui.datepicker //= require common //= require posts //= require twitter/bootstrap //= require owl.carousel //= require turbolinks //= require vendor_js //= require_tree . $(document).ready(function() { $("select#team_select").select2(); }); 

application.css

 *= require select2 *= require_self *= require jquery.ui.accordion *= require jquery.ui.menu *= require jquery.ui.datepicker *= require common *= require owl.carousel *= require lazybox *= require fancybox *= require owl.theme *= require 7531339 *= require_tree . *= require font-awesome 

_form.html.erb

 <%= f.select(:team_id, @teams.collect {|p| [p.name, p.id]}, {include_blank: "None"}, {id: "team_select"}) %> 

What am I doing wrong here? Any help is appreciated.

+7
javascript ruby-on-rails select2-rails
source share
4 answers

The problem is definitely in application.js . According to their Demo App , the sequence of required JS plugins is as follows:

 //= require jquery //= require jquery_ujs //= require turbolinks //= require select2 //= require select2_locale_pt-BR //= require_tree . 

In your case, you need to load turbolinks to select2 , which will result in:

 //= require jquery //= require turbolinks //= require select2 //= require jquery.ui.accordion //= require jquery.ui.menu //= require jquery.ui.datepicker //= require common //= require posts //= require twitter/bootstrap //= require owl.carousel //= require vendor_js //= require_tree . 
+5
source share

I have never encountered this problem when using rails 4.1.5 and select2-rails 3.5.9.3. However, after upgrading the rails to 4.2.4, I get the same exact error described in this question:

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

I managed to resolve this error by removing the "select2-rails" stone from my Gemfile and replacing it:

 source 'https://rails-assets.org' do gem 'rails-assets-select2', '~> 4.0.0' end 
+1
source share

On rails 5 using CoffeeScript and turbolinks I had to use a line:
$(document).on "turbolinks:load", -> before the code $(document).on "turbolinks:load", -> when the desired page with the select tag is loaded.

+1
source share

I had the same problem and changing the order of the JS plugins did not help.

I have finished removing turbolinks and now it works. This is probably not the best solution, but it was the best that I achieved after several hours of searching.

So basically I deleted this line from the application.js file:

 //= require turbolinks 
0
source share

All Articles