Rails Asset Pipeline is not loading my javascript file (why is this code not working
This code works if I include it in the view itself, and it works if I include it directly in the Application.js file, but it won't work if I include it in the assets / javascripts / mailers.js file .. can anyone - ever tell me what i'm doing wrong, thanks.
function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};
Maybe I misnamed it? Here's the code in the view:
<%= text_field_tag :search_mailer, nil, autofocus: true, onkeyup: "myFunction(this.value)" %>
is there anything else I need to add to the mailers.js file I included above? Because that's all there is in this file. The only code in the mailers.js file is:
function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};
source to share
You might have missed including the file in your manifest file. The manifest file will precompile all the .js files in a directory assets/javascripts
into one large file. This is the file that your application is executing. If you don't use your .js file there, it is not included and why nothing happens.
The correct way to include your files is:
//= require mailers.js
in your application.js file. What else, by default you have
//= require_tree .
which requires all js files to be in assets / javascript directory.
if you want to include it specifically for the view, omit the tihs in:
<%= javascript_include_tag "mailers", "data-turbolinks-track" => true %>
To do this, if the precompilation is false, you need 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 problem may also be that the application will pre-compile the wrong file if you have .js and. coffeescript of the same name. You can try running
rake assets:clean
rake assets:precompile
And start the server again.
source to share
Check your layout file. If it javascript_include_tag
's in the title section of the page, try removing it and then placing it just before the closing tag </body>
. Another work around this is to put your code between the document.ready function like this:
$(document).ready(function (){
function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus()
};
};
}
source to share