Inspired? No home

Autocomplete with jQuery in Rails

Autocomplete is very useful so why not add it your site using jQuery? There is a neat part of the latest jQuery UI that does it all very easily.

There is a autocomplete rails plugin made by DHH. So why use this one?

Anything wrong with the jQuery autocomplete plugin?

What you need

jQuery jQuery UI beta

Remember to use the minified versions in production.

How it works


In Rails

Make sure your controller will respond to javascript (or whatever format you prefer to respond with).

The index action in CitiesController must be set up to search for the query paramater (q) and to respond with the javascript format:

def index
@cities = City.find(:all,:conditions => ['name LIKE ?', "#{params[:q]}%"],  :limit => 5, :order => 'name')
respond_to do |format|
format.html # index.html.erb
format.xml  { render :xml => @cities }
format.js # index.js.erb
format.json { render :json => @cities }

Create the index.js.erb view file under views/cities

<% for city in @cities -%>
<%= %>, <%= %> |<%= %>
<% end -%>
On the client

Write javascript/stylesheets in the HEAD section in your layouts/application.html.erb:

<%= yield :head %>

Include the required files (i.e. views/cities/index.html.erb):

<% content_for :head do %>
<%= javascript_include_tag 'jquery-1.2.6.min', 'jquery.ui-1.6rc2/ui/minified/ui.core.min', 'jquery.ui-1.6rc2/ui/minified/ui.autocomplete.min' %>
<%= stylesheet_link_tag 'jquery.ui-1.6rc2/themes/default/ui.all' %>

<script type="text/javascript">
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
$("#q").autocomplete( {
url : '<%= formatted_cities_path(:js) %>',
mustMatch : false
$("#q").autocomplete('result', function(event, data, formatted) {
if (data)
document.location.href = '/cities/' + data[1];
<% end%>

And finally the form on the same page:

<% form_tag cities_path, :method => 'get' do %>
<%= text_field_tag :q, params[:q] %>
<%= submit_tag "Locate city", :name => nil %>
<% end %>
Written on 10 December 2008.
blog comments powered by Disqus