Search code examples
jqueryruby-on-railsjquery-pluginscountries

select country and city any method


I have a page for user registration, but I don't want the user type the city and the country because he maybe type with errors (something like "mexico d,f" other user can type "Mexico D.F.") so I was thinking combobox, but I want also all the cities that a country may have, maybe a jquery or some plugin


Solution

  • First you have to establish the relation between countries and cities. This information will be seed data, and you should choose the solution that suits you best in either keep this information in the DB or in some config file. This will be tricky, cuz countries there are a few hundreds, but cities is almost uncountable. Usually the solution is to make the user choose a country through a select box and let him type the city in which he lives. Maybe then you could query the Google Maps API to check whether that city exists, and use it to validate your form. But if you really want to stick to the combobox solution, you'll have to access a countries/cities database, and that might be hard to get.

    As soon as you tie this knot, the rest is easy. Populate a select box with the country data and then using javascript update the cities select box (or do nothing if you let your user type it... actually you could mitigate the whole issue by using some sort of autocomplete tool). Once you're done with this, you'll just have to validate the data (don't forget to validate the country/city relation in the server, either by using your seed data or some external tool like Google Maps).