Im looking for a good Jquery plugin that can handle finding the country a city belongs to ( on type with autocomplete )
for example:
Typing "New Yor"
Should autocomplete to
New York, United States
And be able to save the city and country as
:city
:country
What would be a good way of achieving such functionality? I mean more in terms of storing all the country's and city's in the user database. I know https://github.com/jim/carmen but that one is being rewritten and I would love to figure this out myself, with a little help.
Might as well write your own logic for this since I don't think a plugin is going to present itself:
I'm assuming the city and country have ids. If not, the logic would actually be simpler. Use jQueryUI's autocomplete to trigger the autocomplete for your element. Add a controller method, that will give your city and country label (likely a method on a city object) along with your ids back as json. In the autocomplete "select" callback, set hidden fields in your form for city and country ids. This last part is optional because I don't know how you plan to persist this data from the form.
The following examples assume A LOT about your app, but should be enough to get you started:
example of script for the view:
$("#yourField").autocomplete({
source: "/path_to_your_action",
minLength: 2,
select: function( event, ui ) {
$(this).val(ui.item.label);
$(this).find("#country_id").val(ui.item.country_id);
$(this).find("#city_id").val(ui.item.city_id);
event.preventDefault;
}
})
controller:
def your_action
term = params[:term]
cities = City.where("cities.name like ?", "%#{term}%")
.limit(25)
.all
render :json=>cities.collect{|c| {:label=>c.your_label_method, :city_id=>c.id, :country_id=>c.country_id}}
end
city.rb
def your_label_method
"#{self.name}, #{self.country.name)}"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With