Reputation: 4053
I have been building a rails 4 app and I need some simple jquery functions. Specifically, I need to run some javascript after a nested_form javascript call (which works fine, but of course was provided). I have scoured the internet and nothing that I find is working even in the slightest (like an alert window once a page is finished loading). Can someone please show me exactly what to do for just a simple alert window on a specific page? The nested_form github shows me how to do the rest. Thank you.
My code:
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= fullTitle(yield(:title))%></title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
...
application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require jquery_nested_form
$(document).onDomReady(function()
{
alert("works1!")
});
$(document).ready(function()
{
alert("works2!")
});
$(document).on('page:load', ready)(function()
{
alert("works3!")
});
$(document).on('nested:fieldAdded', function(event){
alert("works4!");
var field = event.field;
$field.each('input[id=name]').val("testing!");
});
Upvotes: 0
Views: 290
Reputation: 7911
I like to add an additional gem to ensure that jQuery functions appropriately. JQuery Turbolinks fixes the binding events that turbolinks messes with.
Gemfile should then include the following
# Gemfile
gem 'jquery-rails'
gem 'jquery-turbolinks'
gem 'turbolinks'
# application.js
//= require jquery
//= require turbolinks
//= require jquery.turbolinks
Upvotes: 1
Reputation: 11570
With the introduction of turbolinks in Rails 4, you'll have to bind on both $(document).ready
and $(document).on( 'page:load')
. Try changing your code to
var ready = function() {
alert( 'works!' );
// or any other code to execute
};
$(document).ready( ready );
$(document).on( 'page:load', ready );
Upvotes: 3