Ajax autocomplete for two fields


#1

in a form if i have two autocomplete fields in which one depend on
other…

like for ex…if we select country name…all the states should
come …both are autocomplete…

please help me in this regards…

moyeen.


#2

this needs to be DRYed
my app is a “Getting Things Done” type.
so in my “inbox” view I can add it to a project and add context to it
using the ‘take_action’ method.

in my ‘inbox’ controller…
def take_action
@item = Item.find(params[:id])
end

add project and context

def associate_project_context
@item = Item.find(params[:id])
@item.project =
Project.find_or_create_by_name(params[:item][“project_id”])
@item.context =
Context.find_or_create_by_name(params[:item][“context_id”])
if @item.update_attributes(params[:item])
flash[:notice] = ‘Project was successfully associated to item.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

def auto_complete_for_item_project_id
auto_complete_responder_for_projects params[:item][:project_id]
end

def auto_complete_for_item_context_id
auto_complete_responder_for_contexts params[:item][:context_id]
end

private
def auto_complete_responder_for_projects(value)
@projects = Project.find(:all,
:conditions => [ ‘LOWER(name) LIKE ?’,
‘%’ + value.downcase + ‘%’ ],
:order => ‘name ASC’)
render :partial => ‘projects’
end

def auto_complete_responder_for_contexts(value)
@contexts = Context.find(:all,
:conditions => [ ‘LOWER(name) LIKE ?’,
‘%’ + value.downcase + ‘%’ ],
:order => ‘name ASC’)
render :partial => ‘contexts’
end

view with form for the two auto complete boxes

<%= @item.name %>

add a project and context <%= start_form_tag :action => 'associate_project_context', :id => @item %> project: <%= text_field_with_auto_complete :item, :project_id, {} %> context: <%= text_field_with_auto_complete :item, :context_id, {} %>
<%= submit_tag 'add' %>

<%= end_form_tag %>

_context.rthml

    <% for context in @contexts do -%>
  • <%=h context.name %>
  • <% end -%>

_projects.rhtml

    <% for project in @projects do -%>
  • <%=h project.name %>
  • <% end -%>
--------------------------------------------------------------------------

maybe someone could suggest on DRYing it up?


#3

On Mar 22, 2007, at 8:15 AM, moo wrote:

in a form if i have two autocomplete fields in which one depend on
other…

like for ex…if we select country name…all the states should
come …both are autocomplete…

The query for states needs a country id or it is enough to receive
the country name?

– fxn