Rails 4 TurboLinks and jQuery Dynamic Links Not Playing Nice

ctilley79 picture ctilley79 · Jun 30, 2013 · Viewed 16.2k times · Source

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 %>

Answer

thomasstephn picture thomasstephn · Aug 6, 2013

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