Rails, find country based on city with ajax in realtime ( autocomplete)

Im looking for an autocomplete ajax implementation for a textfield.

  • you type your city
  • it wil look for closest match in db as you type
  • as soon as it finds the city (partially search) it displays some options to choose from in format city, state you can pick one from the list and the textfield would contain " city, state"

What would be good ways of doing this in rails? I think i need an autocomplete functionality for this with an ajax posting to the app

Answers


You can find the relevant JavaScript (assuming you're using JQuery) here, from there it's just a matter of setting up a controller action that returns some json and inserting the path to that action to the source: option.

So, very approximately, you'd do something like:

controller:

  class CityController << ApplicationController

    def lookup
      cities = City.find_by_name(params[:city])
      render :json => cities
    end

  end

view:

<%= form_tag do %>
  <%= text_field_tag('city', :id => 'city_input') %> 
  <script type='text/javascript'>
    $(function() {

      $( "#city_input" ).autocomplete({
        source: "<%= lookup_cities_path %>",
        minLength: 2
      });
    });
  </script>
<% end %>

Need Your Help

About value inserting

c# html sql-server

Hey guys I am trying to insert data from gridview label to my double defined entity, following is my line:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.