Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Asset Pipeline is not loading my javascript file (why won't this code work

This code works if I include it in the view itself and it works if I include it directly into the Application.js file, but it will not work if I include it in the assets/javascripts/mailers.js file... can anyone tell me what i am doing wrong, thanks.

function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};

Maybe I am calling it incorrectly? Here's the code in the view:

<%= text_field_tag :search_mailer, nil, autofocus: true, onkeyup: "myFunction(this.value)" %>

is there anything else i have to add into the mailers.js file I included above? Because that is all that is in that file. The only code in mailers.js file is:

function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};
like image 764
ja11946 Avatar asked Dec 14 '22 12:12

ja11946


1 Answers

You have probably missed including the file in your manifest file. The manifest file precompiles all the .js files in the assets/javascripts directory into one large file. This is the file that is running on your application. If you do not your .js file there, it is not included and that's why nothing happens.

The right way to include your files is:

//= require mailers.js

in your application.js file. What's more, by default you have

//= require_tree .

which requires all js files from assets/javascript path.

if you want to include it specifically for the view, drop tihs in:

<%= javascript_include_tag "mailers", "data-turbolinks-track" => true  %>

For this, if precompilation is false, you have to add the file separately: In config/initializers/assets.rb

 Rails.application.config.assets.precompile += %w( mailers.js )

or In config/application.rb

config.assets.precompile += %w( mailers.js )

The issue might be also that the application precompiles the wrong file if you have a .js and .coffeescript file with the same name. You can try running

   rake assets:clean
   rake assets:precompile

And run the server again.

like image 182
Hristo Georgiev Avatar answered Jan 11 '23 23:01

Hristo Georgiev