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

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?

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

Related

JQuery Masked Input Does Not Working in Rails 6

I am trying to use the JQuery Masked Input in my form on Rails 6. But it seems to me that the application.js in assets is not working, i am not sure. I installed the plugin through yarn with the command: yarn add jquery-mask-plugin. It was included in package.json as a dependency.
To setup, I went to app/assets/javascripts/application.js. This is the file:
//= require jquery
//= require jquery_ujs
//= require jquery-mask-plugin
//= require_tree .
$.jMaskGlobals.watchDataMask = true;
In app/javascript/packs/application.js I tried to import the JQuery and the plugin ass well:
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
require("jquery")
import 'inputmask';
Now in my form, this is how I tried to use the plugin:
<%= form.text_field :cpf, class:'form-control', 'data-mask': '999.999.999-99' %>
As I said before, I am not sure, but I think the problem is the application.js file in assets, cause I wrote a console.log("test") command just to see if it is executing and nothing appeared at the web console when the server was running.
Can someone would help me?
yarn add "jquery-mask-plugin"
in app/javascript/packs/application.js
add require
require("jquery-mask-plugin")
in app/javascript/packs/application.js
add line at the buttom
$.jMaskGlobals.watchDataMask = true;
in .html.erb
= d.text_field :phone_number, autocomplete: "phone Number", class: "form-control", placeholder: "03xx-xxxxxxx" , 'data-mask': '0000-0000000'
or
in html.erb
<%= d.text_field :phone_number, autocomplete: "phone Number", class: "form-control", placeholder: "03xx-xxxxxxx" , 'data-mask': '0000-0000000' %>
in app/javascript/packs/application.js
$(document).on('turbolinks:load', function () {
var im = new Inputmask('999.999.999-99');
var selector = $('#person_document');
im.mask(selector);
});
yarn add inputmask
in app/javascript/packs/application.js
require('inputmask');
in assets/javascript/application.js
//= require jquery
//= require jquery_ujs
//= require jquery-mask-plugin
//= require_tree .
//= require jquery.inputmask.bundle.min
$.jMaskGlobals.watchDataMask = true;
in app/javascript/packs/application.js
require('inputmask');
This solved the problem for me.

Rails 5, javascript is not loaded in production

In my app I use the bootstrap theme (gentelella), and in one of my pages I have a Moris graph which works perfect in Development evniroment but in production(heroku) doesn't work.
The error in the console is the following:
**Uncaught ReferenceError: Morris is not defined
**
It looks like the js for the Moris graph(the script is included in gentelella) is not loaded but everything else works fine.
Code for my graph:
<div id="graph_line"></div>
<script type="text/javascript">
new Morris.Line({
element: 'graph_line',
data: [
{Date: 'mydate1', y: myvalue1},
{Date: 'mydate2', y: myvalue2},
{Date: 'mydate3', y: myvalue3}
],
xkey: 'Date',
ykeys: ['y'],
labels: ['Y'],
hideHover: 'auto',
lineColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'],
resize: true
});
</script>
I don't include any Moris.js because it is already included in my theme.
I don't understand why it works fine in local and not in production.
After some researching, I added this line in my production.rb:
config.assets.debug = true
and in heroku logs I have the error:
The asset "application.css" is not present in the asset pipeline
and the app is not running but it runs without the above line.
Any idea why my graph is not working in production and why heroku does not see my application.css
P.S in my assets I have application.scss and not application.css could this cause the problem? But I need the file to be .scss
My application.js:
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.remotipart
//= require pnotify
//= require unobtrusive_flash
//= require flashes
//= require gentelella
//= require gentelella-custom
//= require_tree .
The morris scripts are initialized in the gentellela-custom.js (init_morris_charts();)
And my application.html.erb
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
Update you code to have a debugger reference:
<%= debugger; %> before the line with: new Morris.Line({, and then open your favorite browser, switch to the debugger window and you will have a break point in there.
That will help you see if Morris is loaded at that point in time.

Rails js files & Page specific js

On rails I put all the JavaScript files into application js file.
//= require jquery
//= require jquery_ujs
//= require dropzone
//= require jquery.cookie
//= require toastr
//VENDOR JS BEGINS
//= require pace/pace.min
//= require modernizr.custom
//= require jquery-ui/jquery-ui.min
//= require boostrapv3/js/bootstrap.min
//= require jquery/jquery-easy
//= require jquery-unveil/jquery.unveil.min
//= require jquery-bez/jquery.bez.min
//= require jquery-ios-list/jquery.ioslist.min
//= require jquery-actual/jquery.actual.min
//= require jquery-scrollbar/jquery.scrollbar.min
//= require bootstrap-select2/select2.min
//= require switchery/js/switchery.min
//= require imagesloaded/imagesloaded.pkgd.min
//= require jquery-isotope/isotope.pkgd.min
//= require classie/classie
//= require codrops-stepsform/js/stepsForm
//= require bootstrap-datepicker/js/bootstrap-datepicker
Then I call javascript in the head of application.html.erb as;
...
<head>
..
<%= javascript_include_tag 'application' %>
..
</head>
...
Then I check the speed of the website and I am suggested to take this JS call to body. I know I should BTW. But the problem is with the page specific JS code.
Imagine I have home.html.erb where users select date. So I put datapicker code into this page.
If I take <%= javascript_include_tag 'application' %> into at the bottom of body, this time because the jquery & datepicker not loaded yet so page specific JS gives no method error
What would be the best approach?
Before body close tag and just after <%= javascript_include_tag 'application' %>
add <%= yield :page_scripts %>
Then anywhere (usually on top) in a specific view set your scripts with:
<% content_for :page_scripts do %>
<script>alert( "My nice scripts..." );</script>
<% end %>
There is a very good answer to this at http://brandonhilkert.com/blog/page-specific-javascript-in-rails/.
Basically, you want to open your app/views/layouts/application.html.erb and convince it to give you controller and view information each time it renders a page. To do so you change the body tag from
<body>
<%= yield %>
</body
to
<body class="<%= controller_name %> <%= action_name %>">
<%= yield %>
</body>
So, when rails renders the body tag it will now add a class for the controller and one of the actions in the controller.
Say you have a controller called static_pages, and the static_pages controller has
def home
end
When rails renders the view/page home it will now add to the body tag a class of static_pages and a class of home.
<body class="static_pages home">
the home view is rendered here
</body>
This will be a site wide change, so if you go to an index page/view from the users controller the body tag would be:
<body class="users index">
the index view is rendered here
</body>
Now, make a file called vendor/assets/javascripts/jquery-readyselector.js containing:
(function ($) {
var ready = $.fn.ready;
$.fn.ready = function (fn) {
if (this.context === undefined) {
// The $().ready(fn) case.
ready(fn);
} else if (this.selector) {
ready($.proxy(function(){
$(this.selector, this.context).each(fn);
}, this));
} else {
ready($.proxy(function(){
$(this).each(fn);
}, this));
}
}
})(jQuery);
That file must be properly referenced in application.js
...
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-readyselector
//= require_tree .
Once all that is done you can test it by making a simple alert specific to the view you want test like so:
// app/assets/javascripts/static_pages_home.js
$(".static_pages.home").ready(function() {
return alert("You should only see this on the static pages home page.");
});
// app/assets/javascripts/user_index.js
$(".users.index").ready(function() {
return alert("You should only see this on the users index page.");
});
You could also make a script controller specific by not referencing the action.
$(".users").ready(function() {
return alert("You should only see this on a users controller controlled page.");
});
You can also have a look at Page-specific Javascript for Rails done right. This is worth looking!
Installation
After installation. Let's look at sample code.
var ArticlesController = Paloma.controller('Articles');
ArticlesController.prototype.edit = function(){
// Handle edit article
};
That means that if you have Articles controller's edit action page. Then only the javascript will be triggered. This will not be triggered in other controller actions.

Uncaught TypeError: undefined for Bootstrap Modal

View code:
<div class="modal fade" id="warning_modal">
...
</div>
Javascript:
if (<%= flash[:warning] %> === true ) {
console.log("it's now in the function")
$('#warning_modal').modal({
show: true,
keyboard: true
});
}
My console.log runs and the error is at the $('#warning_modal').modal({ line, it's saying Uncaught TypeError: undefined is not a function. What could be causing this?
Note: I've required bootstrap.js in my application.js file as below, but this does appear to be a loading problem, since in the console, $('#warning_modal') finds the object but $('#warning_modal').modal returns undefined
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require bootstrap.js
Also, I tried adding the bootstrap.js via a CDN as so, but it also didn't work.
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" rel="stylesheet">
</head>
Your modal needs the id="warning_modal", not submit_modal
html:
<div class="modal fade" id="warning_modal">
...
</div>
code:
if (<%= flash[:warning] %> === true ) {
console.log("it's now in the function")
$('#warning_modal').modal({
show: true,
keyboard: true
});
}
As per your update, try this order:
Try this order:
//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require_tree .

How to get the sharebox jQuery plugin to work with Rails

I have downloaded the jquery sharebox from the following site and added what i believe to be the correct code to my app but i am unable to get it to work. I am getting the error messages that
Error: TypeError: $(...).sharebox is not a function.
http://www.jqueryscript.net/social-media/Simple-Clean-Social-Share-Plugin-with-jQuery-sharebox.html
_post.html.erb
<h2><%= link_to_unless_current post.title, post %></h2>
<%= simple_format post.body %>
<div class="demo"></div>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'cathjonesblog'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
comments powered by <span class="logo-disqus">Disqus</span>
<script>
$(document).ready(function(){
$('.demo').sharebox({
services : "facebook twitter google+ linkedin"
});
});
</script>
application.js
//= require jquery
//= require jquery_ujs
//= require foundation
//= require_tree .
//= require jquery.sharebox
$(document).foundation();
application.css
*= require_self
*= require foundation_and_overrides
*= require jquery.sharebox.css
I have placed the js file in my apps javascript directory and the cs files in the stylesheets folder and created an icons folder in the root for the images.
Any help would be greatly appreciated.
Thanks
It sounds like this line:
$('.demo').sharebox({
Might be above this line in the dom:
<script src='/assets/jquery.sharebox.js?body=1'></script>
Dependent javascript files need to be loaded in the right order - eg jquery.sharebox.js calls functions in the jquery library, so the jquery library has to be loaded first. In your case the sharebox plugin has to be loaded before you call .sharebox on that element.
If that isn't the issue, check the console for errors, a js file might not have loaded properly.

Categories

Resources