Search code examples
phpjqueryselectcomboboxcountries

States and Countries select box - best way to do it?


this may seem trivial but I'm setting up, on a profile form page I'm building, a countries and states select box such that when you select the US or Canada then the states box would display states of the selected countries else it would display a None Applicable instead. My countries and states are in a database and I'm populating m y selects from that - I would like a simple yet proper way to do this - I noticed that for some reason disabling select options is not supported in all browsers :( - or is there any nice free snippet online I could use [maybe I'm feeling too lazy to code this here]

I'm using JQuery for the javascripting here though.


Edited

Thanks for the replies - the cascading drop down seems to do what I need but I'm looking for a php based solution.

How have mainstream websites accomplished this btw. Because I don't want to leave it to the user and end with entries including American/ Canadian states with countries that are not the US/Canada.


The Ajax idea is what I had in mind but the thing is that the application form I'm building has a section where you can add contact addresses. Its been built such that you can add multiple addresses to the same contact. Theres an add button which just duplicates the address inputs using a javascript function so basically when you submit the form you have data like :

_POST['address[]'], _POST['city[]'], _POST['state[]'],_POST['country[]']

The thing is binding this action to each instance of state and countries when created.


Solution

  • I think I would not even show the state selector, if neither US nor Canada has been selected from the country selector. This approach has two advantages, users from all other countries are not bothered by meaningless content, you don't have to deal with unwanted input.

    Now I would save the value of the country selector via AJAX and then send/activate the additional selector div with the response, if needed.

    After your edit: How flexible are you then? If you are stuck with some existing code then a cron job which eliminates unnecessary state entries might be another way.

    I mean you could also handle the state later on retrieval but I assume there is also preexisting code which creates addresses and that code doesn't check if the state makes sense...