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 %>
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
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()
Maybe it will help:
$(document).on "turbolinks:load", ->
$('#some_element_id').click ->
alert "Clicked!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With