SyntaxHighlighter

Friday, January 22, 2010

Rails Autocomplete without Ajax (Autocompleter.local)


This was fun - though not easy to find the answer right away.

I wanted to add an autocomplete to a form, but I wanted the suggestions to be local (I didn't want to make any ajax requests, I wanted to use a pre-defined javascript array).

This ended up to real easy.

The scenario here - I have a nested set of objects that an admin may want to give membership privileges to an existing user in their system. The number of existing users, is low (< 100).

For this to work, I had a @member_emails variable accessible to the view. This held all the emails from members that were already members somewhere else in the system.

With this, admins are able to access existing users or add new users quickly.


<%= f.label :user_email, "User's email" %>
<%= f.text_field :user_email, :autocomplete => "off" %>
< div class="auto_complete" id="user_email_auto_complete" >< /div >

<%= javascript_tag("new Autocompleter.Local('membership_user_email', 'user_email_auto_complete', [#{ @member_emails.map{|e| "'" + e + "'" }.join(',') }] , {fullSearch: true, frequency: 0, minChars:1});") %>

No comments:

Post a Comment