Countries dropdown that will automatically change

2019-08-24 01:16发布

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...'

3条回答
做自己的国王
2楼-- · 2019-08-24 01:32

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

查看更多
beautiful°
3楼-- · 2019-08-24 01:47

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

查看更多
forever°为你锁心
4楼-- · 2019-08-24 01:48

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.

查看更多
登录 后发表回答