Countries dropdown that will automatically change

2019-08-24 01:01发布

问题:

I need to use some javascript (ideally jQuery) to display a dropdown menu of countries and once selected this will display another dropdown with regions from that country selected.

I'm guessing i'd need some API as their would potentially be loads of options.

e.g User selects 'United States' Auto show new dropdown with US states 'Alabama etc...'

回答1:

Here is a jQuery plug-in which allows you to easily make cascading drop down. I am not sure what service you will use to get names of all countries, but you can take a look at geonames.

Edit: Check this jsfiddle demo too. Looks nice.



回答2:

The way I would try doing this is storing the list of regions (or states) in an object.

regions = {
    unitedstates: ["East Coast", "Mid-West", "West Coast"],
    canada: ["Vancouver BC", "whatever", "whatever"],
    cont...
    }

Then create the new list and append it to the DOM, and use a function to build the options based on what's clicked.

for (i = 0; i < regions[selection].length; i++){
    newlist.howeveryouaddanoption(regions[selection][i]);
}

Unsure how to use Javascript to build a dropdown list but that would be my strategy



回答3:

Here's a library I wrote for doing exactly this. It's very simple - the tricky part (read: time-consuming!) was just getting all the country and region data all populated.

https://github.com/benkeen/country-region-selector