How to add JQuery AutoComplete to your Rails Forms In a RESTFUL WAY?
JQuery is a very easy to use javascript library, go to http://jquery.com to find out more. Also there is a nifty little plugin called jrails that will remove Prototype and Scriptaculous and replace it with the jquery core libraries.
STEP 1
Once you have JQuery installed in your app, all you need to do is to add the jquery.autocomplete.js plugin http://www.dyve.net/jquery/?autocomplete to your javascripts directory and add a javascript include tag to your layout view. There are several autocomplete plugins to choose from, I really liked Dylan Verheul’s plugin and this example uses it.
LAYOUT VIEW
STEP 2
Next in the controller that you want the results to feed from change your index action to accept a “q” parameter. And modify your respond_to section to accept a js format.
RESTFUL INDEX ACTION
STEP 3
Next create a javascript index file in your categories view folder called “index.js.haml”
RESTFUL VIEW
This will render a text list of categories for the Query Auto Complete
STEP 4
Check your view and make sure you verify the id tag to be #{model}_#{field}.
ie product_category
VIEW
STEP 5
In jquery you can find elements by using their id preceded by a pound sign. So in the application js file we add the autocomplete method in the ready block.
JAVASCRIPT
FINISHED.
That’s it now you should have your autocomplete up and running. You can view the whole query.autocomplete.js documentation on http://www.dyve.net/jquery/?autocomplete
It really is just that easy, and it also makes working with autocomplete so much easier in complex forms using virtual attributes.