Ajax autocomplete highlighting

Posted by tohchye

Autocomplete text field is a very useful feature to speed up form completion and help minimize errors. It’s even better if you can highlight the keywords within the dropdown list to help user search for the right choice. Here’s how to implement keyword highlighting in rails.

1. First add the necessary javascripts to make the text field into an autocomplete text field.

form
<%= text_field_tag 'country', '', :id => 'country' %>
<div id="country_autocomplete" style="display:none"></div>
<script type="text/javascript">
//<![CDATA[
var country_auto_completer = new Ajax.Autocompleter('country', 'country_auto_complete', 
  '/countries/auto_complete_for_country', frequency:0.2})
//]]>
</script>

2. Then in the controller add in the method to find the list of items base on the keywords and assign the keyword to an instance variable (this is needed for the highlighting).

controller
def auto_complete_for_country
  @keyword = params[:country]
  @countries = Country.find(:all, :conditions => ['name like ?', "%params[:country]%"])
  render(:partial => 'auto_complete')
end

3. In the view, create the highlighting effect by replacing all keywords within the country names with ‘keyword’ using the ‘strong’ tag.

view (_auto_complete.rhtml)
<ul>
<% for country in @countries do -%>
<li><%=h(country.name).gsub(Regexp.new("(#{@keyword})", true), '<strong>\1</strong>') %></li>
</ul>
Comments

Leave a response