$ is not defined, Uncaught ReferenceError while using Select2 plugin with Rails

不打扰是莪最后的温柔 提交于 2019-12-24 00:27:58

问题


I'm trying to use the Select2 plugin to add a search bar to my select box.

I get the following error when looking at the page console :

Uncaught ReferenceError: $ is not defined

Searching different questions here led me to believe this error happens because the jQuery javascript is not included or put before the script is called. But I still could not find a way to make it work. How can I fix this error and make the select2 plugin work?

Here is the application.js file :

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require select2
//= require tinymce
//= require turbolinks
//= require_tree

I've tried rearranging the order of select2 in the application.js file in many different ways with no success (I tried to make sure jQuery was loaded right before Select2).

Here is the index.html.haml file :

%select{:id => "test"}
    - @lamps.each do |lamp|
        %option{:value => "1"}= lamp.brand + ' ' + lamp.category + ' ' + lamp.lamptype + ' (' + lamp.cct.to_s + 'K)'

:javascript
    $(document).ready(function() { $("#test").select2(); });

Here is the application.html.haml file :

!!! 5
%html
  %head
    %title= t('.lspdd_light_spectral_power_dis')
    %meta{:name => "viewport", :content=>"width=device-width, user-scalable=no"}
    = stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true
    = javascript_include_tag "application", "data-turbolinks-track" => true, :defer => "defer"
    = javascript_include_tag "d3.min.js", :defer => "defer"
    = csrf_meta_tags

Additionnal information :

  • Rails version : 4.0.3
  • ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]

Thank you!

Edit #1:

Adding the a screenshot of the information displayed by the network dev-tool.

http://imgur.com/QJGCM2b

If I understand correctly the application-ea826f14bc5ea6f6976b187ce8d3008e.js file includes everything mentionned in the application.js file?


回答1:


dont use //= require_tree if you already include all you scripts manualy. this can be the cause of errors. remove this string and try to reload page

p.s i also think what you are using incorrect sintax

//= require_tree

correct version contain dot

//= require_tree .

p.p.s. not about your main question, but you are using old version of ruby. check the newer

one more important thing what i didn't mentiond before. you are using defer="defer" attribute for deffering main script loading. inline javascript what you type on page loaded BEFORE main scripts



来源:https://stackoverflow.com/questions/35205226/is-not-defined-uncaught-referenceerror-while-using-select2-plugin-with-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!