Reputation: 2195
I am developing an application in Rails 4.0 and I'm having an issue with turbolinks not playing nice with some jQuery code I have. I have a Quote model that has a related QuoteItems model. I am using accepts_nested_attributes_for and some jQuery to populate the line items form.
When I click on a link bringing me to the new_quote_path, The dynamic link doesn't fire the javascript code. When I refresh the page, the form WORKS GREAT. I like turbolinks as it is super fast, but not sure how to get this to work in development. Here's some code.
in quotes.js.coffee
jQuery ->
$('form').on 'click', '.remove_line_items', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
Quotes view new.html.erb
<%= form_for @quote, :class => "hello" do |f| %>
<fieldset>
<p>
<%= f.label :quote_date, "Date of Quote" %> <br/>
<%= f.text_field :quote_date %>
</p>
<p>
<%= f.label :good_through %> <br/>
<%= f.text_field :good_through %>
</p>
<p>
<%= f.label :quote_number %><br/>
<%= f.text_field :quote_number %>
</p>
<p>
<%= f.label :customer_id, "Customer" %><br/>
<%= select(:quote, :customer_id, Customer.all.collect {|c| [ c.fname, c.id ] }, :prompt => "Select Customer") %>
</p>
<%= f.fields_for :quote_items do |builder| %>
<%= render 'quote_item_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "Add Line Item", f, :quote_items %>
<p>
<%= f.submit %>
</p>
</fieldset>
<% end %>
Upvotes: 10
Views: 16443
Reputation: 1189
Maybe it will help:
$(document).on "turbolinks:load", ->
$('#some_element_id').click ->
alert "Clicked!"
Upvotes: 4
Reputation: 3835
I was having the same problem, if you want to keep turbolinks working and your dynamic jquery on, try this gem: jquery-turbolinks
Hope it helps
Upvotes: 16
Reputation: 20624
Some options:
1) turn off turbolinks - see http://blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4
2) use new page:load
event that turbolinks fires - $(document).on('page:load', your_start_function);
, see Rails Jquery doesn't work on other pages - guessing in your case it would be something like
$(document).on 'page:load' ->
$('form').on 'click', '.remove_line_items', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
Upvotes: 9
Reputation: 432
Turbo links uses AJAX which means any dynamically generated elements never get their ready events assigned (because the page isn't technically loading after the first load). Instead, you need to listen to the top DOM element body
or document
and then specify a selector for the dynamic element to listen to:
$('body').on('click', '.remove_line_items', function(e) { ... });
Upvotes: 3