Skip to main content

jQuery and Turbolinks not playing nicely

General • Asked by shakycode

Ok, so I'll try to make this brief.

I have a new Rails 4.2.1 app using Ruby 2.2.2 and I'm trying to do a live search on a basic crud model. I have ransack installed and it's working great. But I'm having problems with the jQuery ready/Dom binding in my jQuery to get the live search working.

I've installed jquery-turbolinks and now things like select2 work properly, which is great. But when I go to search using keyup in the JS the first two letters will get parsed in params and no other results will show up as i continue to type. Also if I backspace the search text it doesn't scope to super.

Here's my view:

index.js.erb

$("#search").html("<%= escape_javascript render("search") %>");
$("#results").html("<%= escape_javascript render("results") %>");

_search.html.erb

  <div class="pull-right" style="margin-right: 25px">
    <%= search_form_for(@q, url: "/inventory", method: :get, :id => "inventory_search", :remote => true) do |f| %>
      <%= f.search_field :asset_number_or_asset_name_or_asset_serial_cont, placeholder: 'Search...', class: 'form-control'%>
    <% end %>
  </div>

_results.html.erb

<table class="table table-striped">
  <thead>
    <tr>
      <th>Asset Number</th>
      <th>Asset Name</th>
      <th>Serial Number</th>
      <th>Model</th>
      <th>Manufacturer</th>
      <th>Asset Type</th>
      <th>Actions</th>
    </tr>
  </thead>

  <tbody>
   <% @assets.each do |a| %>      
      <tr>
        <td><%= a.asset_number %></td>
        <td><%= a.asset_name %></td>
        <td><%= a.asset_serial %></td>
        <td><%= a.asset_model %></td>
        <td><%= a.asset_manuf %></td>
        <td><%= a.asset_type.try(:name) %></td>
        <td><%= link_to 'View', inventory_path(a), :class => 'btn btn-mini btn-info' %> <%= link_to 'Edit', edit_inventory_path(a), :class => 'btn btn-mini btn-warning' %></td>

      </tr>
  </tbody>
  <% end %>
<%= will_paginate @assets %>

Here's my JS

application.js

 $(function(){
    $("#inventory_search input").keyup(function() {
   $.get($("#inventory_search").attr("action"), $("#inventory_search").serialize(), null, "script");
    return false;
    });
    });
});

I think I'm calling jQuery ready properly by declaring the function to load the dom and bind. But honestly my jQuery sucks so I'm probably missing something. Anyone have any idea what's happening here? This code worked great in Rails 3.2.x when I wrote it originally, but it's not really usable in 4.2.x with Turbolinks.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.