AutoComplete Textbox in rails
in Ruby on Rails adding auto complete textbox is pretty simple. here is a simple example of it that I have done in one of my rails project...
in this example there is supposed to be 1 table in DB. i.e., Projects table.
When User types in the alphabets in the textbox it will show the related projects.
we need to download the plugin Auto_complete.
1. download auto_complete plugins from github
2. unzip the downloaded zip folder and rename the folder 'auto_complete'
3. store 'auto_complete' folder in the "\vendor\plugins\" folder. [i.e. \vendor\plugins\auto_complete]
4. now, open the file 'index.html.erb' in views\projects\ folder, and add the following line before tag
<%= javascript_include_tag :defaults %>
<div>
<%= text_field_with_auto_complete 'project', 'name',{}, :skip_style => false %>
</div>
5. open projectsController and add this line
skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_project_name]
after this
class projectsController < ApplicationController
6. add this new function in this controller:
def auto_complete_for_project_name
project_name = params[:project][:name]
project_name = project_name.downcase if not project_name.nil?
@projects = Project.find(:all , :conditions => ["name like ?",'%'+project_name+'%'])
render :partial => 'project'
end
7. now create a new partial file in app\views\projects and name it _project.html.erb
8. paste this code in this partial file
<ul>
<% for project in @projects do %>
<li><%= project.name %>
</li>
<% end %>
</ul>
9. now restart server and in the browser go to http://localhost:3000/projects and now in the to field start typing u'll see some name coming from DB.
10. so its woking !!!!!!!!!!!!!!!!!!!!!!!!!!!