Rails Auto Complete with jQuery/jRails

Having long used jRails in place of of scriptaculous/prototype with my Rails projects, I found that the latter won’t work with the original auto_complete plugin for Rails.

So I tried a few solutions such as this which uses the auto_complete_jquery plugin, as well as more involved solutions such as this and this one which uses HAML. However, I didn’t want to write javascript and also have all the helpers of the original plugin, to implement the solution presented in Railscast 102, with a RESTful call to the correct controller (the original plug-in doesn’t work RESTfully in its default configuration).

I ended up using the jrails_auto_complete plugin and it works fine so far. Be sure though to include all js files included with project. Aside from some minor styling issues it seems to work just like the original auto_complete plugin with the same helpers and the code used in the Railscast.

Here’s a sample text_field_with_auto_complete tag using the auto_update_element/afterUpdateElement callback which fires when the selection is made:

<%= text_field_with_auto_complete :hotel_search,  
  :destination_code, {:size => 30 },  
  {:url => (destinations_path(:format => :js)),  
  :method => :get,   
  :param_name => 'search',  
:after_update_element => "function(element,value){alert('You have chosen ' +  
} %>

Of course this cries out for being extracted into a helper but it can be hard to get the syntax right, especially for the callback.

sam: does this work for you in safari too? I tried but i couldnt use the keyboard to select items. What version for jquery & rails are you using?

Posted: 04 August 2009

comments powered by Disqus