You can use a JavaScript to add all the country names and state names’ Dropdown list. Which is actually done by HTML <select> and <insert> tag. I’ve written a JavaScript which can be simply inserted into your HTML file. Later, call my pre-defined functions and the country and state list will be automatically added into your HTML
Live Demo!
How to use?
1. Download Source Code (Latest Version) from here
Unzip and get the .js file
2. Put this code between your <HEAD> and </HEAD> section:
<script type= "text/javascript" src = "countries3.js"></script>
3. Put this code between your <BODY> and </BODY> section:
Select Country:
<select onchange="print_state('state',this.selectedIndex);" id="country" name = "country"></select> <br />
City/District/State:
<select name ="state" id = "state"></select>
<script language="javascript"<print_country("country");</script>
Please note that, we are using two <select> tags, which are actual drop-down boxes. Here I’ve chosen “country” and “state” as their ID attribute. You can choose any othe id attribute or name attribute as you like. But whatever you choose, you make to pass the correct IDs when calling the JavaScript Functions.
If you only want Country list to appear on the page, Simply use following bit of code in Body section:
Select Country: <select id="country" name ="country"></select>
<script language="javascript">print_country("country")</script>
You’ve to pass the ID of <select> element in print_country function, which actually prints the names of the countries.
Disclaimer: I’ve collected the names of countries and states from internet, and of course, cannot authenticate their validity!
Happy Coding
![]()

Hi, I am working in your example,It works perfectly in Firefox but in IE does not insert any item in the list, Do you know what is the problem?
Thanks for notifying me. I’ll work on it to find a valid solution
hello,
ya it doesn’t work with ie,i have tried to put option tag and call the function i get all of them in one line.
any solutions?
Dear Friend, I’ve fixed the bug
Please grab version 2.0 which works on IE:
http://countries.sourceforge.net/countries2.zip
Here is an alternative: http://javascript.internet.com/forms/country-state-drop-down.html
Great if you only want US, Canada, UK and a VERY FEW other country states/provinces! Otherwise absolutely USELESS
Hi, thanks for the script. I’ve found that the State drop down doesn’t reset when going from a large list i.e. UK to a small list, the remainder of the options still stay there. I have added in “option_str.length=0;” to the print_state function to reset the list.
Regards
Thank yeah very much for the fix
It saved my time. Very good script.
Countries2.zip eliminates all the bugs.
You are a good player of Javascript
Row content is correct. It contains all the states of India. Its perfect. I’m from India.
Thanks for your comment. I really appreciate it!
I have a problem with this script: If someone accidentally selects the WRONG country, and then selects the right one, under the list of states etc, the states from the wrongly selected country will show below those from the current country. Is there a way to flush the state drop-down when another country is selected to avoid this happening?
Regards
Glen
Just seen Julian’s comments above and used the ‘fix’ – that works perfectly.
Got another problem here now. I need to dynamically insert the previously selected Country and State [read from the Member Db] as selected option, whilst still allowing the member to select any other Country and/or State. I am using asp and the db fields are called with the following code:
for Country:
for State:
99% of the time a member won’t be making a country change – more likely a state/province/county change.
Anyone have any ideas? I have tried the ‘ststic’ route by inserting:
<option selected value="”>
into the select box itself, but although the current state shows, the Country select box shows the ‘Select Country’ option.
Bits got stripped out of my message. If you can help, please eMail me and I will give the full code.
Regards
Glen
Here goes the code Glen mailed me. I think involves some asp.net/c# tags
Hi, Would it be possible for you to let us know where you got the data from ?
I would like to populate some SQL tables with this data but it might be easier using the original source.
Regards,
Mark
Hi, first off thanks for the script it is perfect for location entries.
I am having the same issue as Glen in that when a user goes to their edit profile page I want the current country and state/province they have in the db to be selected.
Is there a way to use an if statement within this code so that when the option fields are being generated if the current option equals what is in the database, that option will be selected.
Anyone have any ideas? I am better with PHP than Javascript so a push in the right direction would be appreciated. Glen did you solve your issue (again I am using PHP though)?
Unfortunately I haven’t solved this one yet. I am sure it is possible both in classic asp as I am using, and PHP as you’re using. It may just be a syntax thing in the javascript that I am getting wrong, so it ignores or ‘falls over’ when it tries to read the Db data in. I can get the country to work though … but it isn’t the country people would want to change – more the state.
Glen
Pingback: JavaScript Country State List « Jan Souza – my Projects
Hi,
Very simple and cool your project.
Thank you, help me a lot.
I put default select in your code.
http://jansouza.com/2010/10/13/javascript-country-state-list/
Feel free to use on your main code.
Thank you.
/*
* Atenciosamente/ Regards/ Saludos,
* Jan Souza – http://jansouza.com
*/
Hi
I am using this script to my page but it generate function(iteration) as many times in countries as well as state select boxes.. I need solution for this ! plz
after selecting a country such as USA then selecting another such as Australia I noticed the region/state option would append in FF.
option_str.options.length = 0; // inserting this will fix the issue
// put it just above the following line in print_state()
for(x in state_arr){
I’ve added Julian’s fix (also thanks to Ross to rediscover it
) and fix by Luigi Balzano
Released a new version (3.1)
Thanks guys for supporting this project
Czeck Republic should be Czech Republic
For a list of districts in New Zealand try: http://www.statoids.com/ynz.html
Awesome Script.
I added a few features fo my own use that you might want to add back into the code
Support for country and state codes
– US State Codes
– Canada Province codes
– Country Codes
– Support for easy reordering of countries
http://www.savrus-support.com/countries.zip
Thank you.
Hi,
Does anyone know where exactly in print_state’s function to put in “option_str.length=0;” ?
I am having the same problem as Glen. But I have no idea where to slot that code in.
I am no javascript-er.
Would appreciate if someone could answer this? Thanks!!
YIKES..sorry! My bad.
Realized i hd been using the outdated version of this thing didnt know there are newer files in the folders @ sourceforge.
THANKS
Anyone know how to incorporate this into a wordpress site?
eg)
A directory that is like craigslist, so same topics but in different cities, countries. People would search or add content only in their specific city or country.
ie ) Two locations: Los Angeles and New York. Type of places: clubs, bars, restaurant. Person can choose to search based on city and type of place.
I’ll extend it for wp
amazing one… ll help for my website form
also try for cities for all countries .. its big task want help from me mail me to ajaypatel_aj@yahoo.com
Terrific submit man. For those who are enthusiastic about Cura de slabire evening me.
Very good script, but I need country/state data list on XML spreadsheet (column A : country and column B : related state) I’m appreciated if someone can help me put them on XML file.
Hello all! I like this forum, i organize many inviting people on this forum.!!!
Great Community, respect all!
thank you…
hi i tried to use it with jquery.jqtransform.js it doesn’t work.
very Good Script .thank you………
just intimate print error on display instead this print_country(“country”);
our code is <script language="javascript"<print_country("country");
its wonder
I noticed that the list does not clear out completely if you end up selecting more than 1 country (user sometimes
could select the wrong country)
As a test I selected Vietnam first, then selected a city in the list. I then selected USA.
When you look in the list of cities it now shows both USA cities and part of the Vietnam cities in the list.
I tried this with both Firefox (ver 8) and Chrome (ver 16).
Besides that it is a good script and saved me a lot of coding.
thankx for this and it’s a good script
So far i facing 1 problem, I cannot get the selected value from the list.
I use runat = “server” between the , so that i can use it at code behind :
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = country.Value.ToString();
}
It always return ‘ ‘, or ’0′ if i change the ‘Value’ to ‘SelectedIndex’. someone please help me =(
I modified Jan Souza’s code further by adding default State along with his default Country. Here’s the changes to the last two functions.
function print_country(country_id, selected, state_selected) {
var indexSelected = 0;
// given the id of the tag as function argument, it inserts tags
var option_str = document.getElementById(country_id);
var x, i = 0;
for (x in country_arr) {
option_str.options[i++] = new Option(country_arr[x], country_arr[x]);
if (selected && country_arr[x] == selected) {
//alert(selected);
indexSelected = i – 1;
}
}
if (selected) {
option_str.selectedIndex = indexSelected;
print_state(‘state’, indexSelected, state_selected);
}
}
function print_state(state_id, state_index, state_selected) {
var option_str = document.getElementById(state_id);
option_str.length = 0; // Fixed by Julian Woods
option_str.options[0] = new Option(‘Select State’, ”);
option_str.selectedIndex = 0;
var state_arr = s_a[state_index + 1].split(“|”);
for (var i = 0; i < state_arr.length; i++) {
if (state_arr[i].toLowerCase() == state_selected.toLowerCase())
option_str.options[option_str.length] = new Option(state_arr[i], state_arr[i], true, true);
else
option_str.options[option_str.length] = new Option(state_arr[i], state_arr[i]);
}
}
To use, add the following to the HTML:
print_country(“country”, “USA”, “Virginia”);
Enjoy!
i used this bro but it does not works plzzz…. help me for select some defualt country and state
Hi Shafiul Azam,
I really appriciate your work.
But if you can provide cities then please inform me as soon as possible, i need them.
Hi It is very nice code & Useful. It save time
but i face same problem that melvin have.
i can’t get the user selected value
Are you using my code directly/made any other modifications? It’s suppose to work as standalone javascript only!
Hi shafiul
just a quick question is there a way to add 2 more so it’s
country, region, county and city.
I have the values stored in my db but I can’t get them to populate? Is there an easy way to change your code
hey…
i need to include country.js in dropdown but i want to populate that drop down dynamically on every button click using asp.net/C#..can anyone help
It is good try to make the things fast. If you try this from Ajax + jquery this would be more batter. There are some corns it this approach. Number one all values of countries and states make the large HTML page. This will slow down the page load. Number if you dont want to grab page information from any others then it is hard to protect.
I am sure if you use jquery approach then performance will not effect any more. It is true this approach is fast while changing the dropdown value. but same this slows the page load.
I need to have 3 dropdown using javascript,,,such as country-state-district….Please help me with source code…
I used the countries and state script you provided…Thanks for that..please help me out in this…Thanks in Advance….
This is an easy to use code to select records from MySQL database table and display in dropdown combo box using PHP.
$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = “SELECT field_name FROM table_name”;
$rs = mysql_query($sql) or die(mysql_error());
echo “”;
while($row = mysql_fetch_array($rs)){
echo “”.$row["field_name"].”";
}mysql_free_result($rs);
echo “”;
Source:
http://phphelp.co/2012/05/10/how-to-fill-
a-dropdown-combo-box-in-php-from-mysql-database-table/
OR
http://addr.pk/a8cf
Not sure if the ‘please show the previously selected value’ has been fixed, but if you pre-set the value of the country outside the function – (e.g. “mycountry”) AND pre-set the state (e.g. “mystate”) then call the print_country(‘country’) function with this small change…
if (country_arr[i] == mycountry) {
option_str.selectedIndex=i+1;
print_state(‘state’,option_str.selectedIndex);
}
It will work.
Likewise, the print_state function should include this line of code…
if (state_arr[i] == mystate) {
option_str.selectedIndex=i+1;
}
This works in IE9, no other browsers tested.
One more minor refinement – if you want to be able to use the states for mailing purposes (in the USA), you can change s_a[239] as follows:
s_a[239]=”AL Alabama|AK Alaska|AZ Arizona|AR Arkansas|CA California|CO Colorado|CT Connecticut|DE Delaware|DC District of Columbia|FL Florida|GA Georgia|HI Hawaii|ID Idaho|IL Illinois|IN Indiana|IO Iowa|KS Kansas|KY Kentucky|LA Louisiana|ME Maine|MD Maryland|MA Massachusetts|MI Michigan|MN Minnesota|MS Mississippi|MO Missouri|MT Montana|NE Nebraska|NV Nevada|NH New Hampshire|NJ New Jersey|NM New Mexico|NY New York|NC North Carolina|ND North Dakota|OH Ohio|OK Oklahoma|OR Oregon|PA Pennsylvania|RI Rhode Island|SC South Carolina|SD South Dakota|TN Tennessee|TX Texas|UT Utah|VT Vermont|VA Virginia|WA Washington|WV West Virginia|WI Wisconsin|WY Wyoming”;
Save the entire entry (e.g. WI Wisconsin)
Then, when you want to print a label, just use the first two letters for the state.
I don’t know how it works in other countries, but 2-digit states work best in the USA.
Can you send the code to generate country code like for India == 91 like this please i need it for my blog.
hey man thanks for the tutorial:
I’m getting he following error:
Uncaught ReferenceError: print_country is not defined register.jsp:113
(anonymous function)
I have the exact same code you posted. Any ideas why I’m getting this error.
I don’t know whether you should put this code in a file containing JSP code. It’s suppose to work on client side script like JavaScript or in your HTML page.
Hey thanks for the reply.
Kind just tested on a HTML page and it is giving the same error message when debugging.
I made some changes to it and now it is partially working. The list of countries displays but the list of states is not.
I get this error when I debug:
Uncaught ReferenceError: state_index is not defined countries.js:292
print_state countries.js:292
onchange
Hi,
How can i include this in Contact Form 7 for WordPress??
Thanx in advance
No Idea. This is not any WP module
Hi Nice code . Please provide city code too.
Thank you for your valuable script, and the great efforts in the research of the countries. You are king!
For those of you who are experiencing the state populating with a previous country’s state list use this code in the countries2.js to fix it.
//REPLACE
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
var x, i=0; state_index++;
var state_arr = s_a[state_index].split(“|”);
for(x in state_arr){
option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
}
}
//WITH
function print_state(state_id, state_index){
document.getElementById(state_id).options.length = 0;
var option_str = document.getElementById(state_id);
var x, i=0; state_index++;
var state_arr = s_a[state_index].split(“|”);
for(x in state_arr){
option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
}
I have added this line that makes the difference (clears all previous values before populating):
document.getElementById(state_id).options.length = 0;
}
Hi, i hv used ur code but it doesn’t display the country list,state ?? I followed your instructions.
Plz help..
can you please explain the function print_country and print_state working. i did not get the point when i selected the country how the print_state function function works, what are the arguments doing in both the function? and why we need x and i variable?.what actually the onchange event doing?,what is the use of .options property ?? i want to change the script little bit but not able to undestand it properly. plz help me asap.
I want add another dependent drop down menu after the “state” and I tried to add the following code.But, is not working ,a can anyone help?
Select Country:
City/District/State:
School/college:
print_country(“country”);
print_state(“state”);
print_college(“college”);
In the HTML:
Select Country:
City/District/State:
print_country(“country”);
College:
print_country(“country”);
——————————————————————————————————————
In the COUNTRIES.JS:
//Create an array for all the college name options
ar c_a = new Array();
c_a[0]=”";
c_a[1]=”College Name for Country 1|College Name 2 for Country 1|College Name 3 for Country 1″;
c_a[2]=”College Name for Country 2|College Name 2 for Country 2|College Name 3 for Country 2″;
……
c_a[252]=”College Name for Country 252|College Name 2 for Country 252|College Name 3 for Country 252″;
//College
function print_college(college_id, college_index){
document.getElementById(college_id).options.length = 0;
var option_str = document.getElementById(college_id);
var x, i=0; college_index++;
var college_arr = c_a[college_index].split(“|”);
for(x in college_arr){
option_str.options[i++] = new Option(college_arr[x],college_arr[x]);
}
}
Hope that helps
Sorry the HTML part didn’t display properly let me try again:
Country:
Province/District/State:
print_country(“country”);
College:
print_country(“country”);
*make sure there isn’t a space between the “<" and "select" / "script".
Thanks for the great tutorial, I’ve found it extremely helpful!
Is there a way to set up a default option for the drop down menu so that it looks like:
Select Country: Choose Country
City/District/State: Must First Choose Country
Since if I wanted to choose Afghanistan I have to select a different country and then go back to Afghanistan in order for the City/District/State to display.
Once again thanks for the great tutorial
Thanks for the code and explanation!! Appreciate it very much =)
Thanks so much, rly help
Thanks for your coding. I found ur coding very helpful. i request for cities as state is selected. will i get that coding
I added some code by studying jansouza code…
adding country and state on the same time…
function print_state(state_id, state_index, state_selected){
var indexSelected = 0;
var option_str=document.getElementById(state_id);
var x,i=0;
state_index++;
var state_arr=s_a[state_index].split(“|”);
for(x in state_arr){
option_str.options[i++]=new Option(state_arr[x],state_arr[x]);
if (state_selected){
if (state_arr[x]==state_selected){
indexSelected = i-1;
}
}
}
if (state_selected){
option_str.options[indexSelected].selected = true;
}
}
function print_country(country_id,countrySelected, stateSelected){
var indexSelected=0;
// given the id of the tag as function argument, it inserts tags
var option_str = document.getElementById(country_id);
var x, i=0;
for(x in country_arr){
option_str.options[i++] = new Option(country_arr[x],country_arr[x]);
if(countrySelected && country_arr[x] == countrySelected){
//alert(countrySelected);
indexSelected = i-1;
}
}
if(countrySelected){
option_str.selectedIndex = indexSelected;
print_state(‘state’, indexSelected, stateSelected);
}
}
usage :
print_country(“country”,”Indonesia”, “Nusa Tenggara Barat”);
Why didn’t you use the country and state codes in the dropdownlists values? It is repeated as the text and value for each dropdown item.
Neat indeed …. would there be anyway to develop a way of using a google map address lookup (jquery map) that automatically uses the lat/long position of the person signing up and then “completing” the data by adding a country code and state info utilising your method above?
i copy the jscript as calendar2.js & insert the html code in my prog.But i don’t get the dropdown list contents.Empty dropdown list apeear on my screen
Rewrote these functions adding a default country / state. Seems to work
function print_state(state_id, state_list_index, setState){
var option_str=document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option(‘Select State’,”);
option_str.selectedIndex = 0;
var stateIndex = 0;
var state_arr=s_a[state_list_index].split(“|”);
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
if (setState && state_arr[i] == setState){
stateIndex = i+1;
}
}
if (setState){
option_str.selectedIndex = stateIndex;
}
}
function print_country(country_id, setCountry, setState){
// given the id of the tag as function argument, it inserts tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option(‘Select Country’,”);
option_str.selectedIndex = 0;
var stateListIndex= 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(setCountry && country_arr[i] == setCountry) {
stateListIndex = i+1;
}
}
if(setCountry) {
option_str.selectedIndex = stateListIndex;
this.print_state('state', stateListIndex, setState);
}
}
B this is great but I’m new to JS and was wondering where I designate the default Country and State.
Thanks
The default country and state parameters are sent to the print_country function of countries.js which is called after you create the select boxes. I am using PHP to pull the default country and state out of a database if it exists, and use it as my defaults. You could simply pass “USA”, “California” if you wanted.
Select Country:
City/District/State:
print_country(“country”, “defaultCountry”, “defaultState”);
The function you call is print_country. If you pass it defaults, those will appear in the select menu. If you only pass it the ID Attribute (“state” and “country” are the ID attribute of my 2 select boxes) It gracefully displays the standard select box.
lol that did not paste gracefully. See it here
http://nopaste.info/eeebfb1f16.html
B, I tried your code and I wasn’t able to get the system working. Even when I only input print_country(“country”) I don’t get anything in the drop down menus. Is there something else I need to do to the code beyond removing the code for the functions that was already there and pasting in your code? Is there anything I need to do when writing the new code into my HTML page?
Are you including the js file in the head of your html?
is the id of your country select box “country”?
did you call the function after your html code for the select box?
I have called the java script in the Head section and when I don’t use your new functions in the Javascript file it works fine so that can’t be the problem.
The id of my country is country and I call the script after the select boxes.
I have copied my code below, let me know if you see the error in the code. I changed the country from USA to United States in the javascript code so I know that can’t be the issue either.
Thanks
Country
State
print_country(“country”, “United States”, “New York”);
Sorry just realized the code didn’t paste well.
/
/
/Country
/
/
/
/
/
/State
/
/
/
/print_country(“country”, “US”, “NY”);
/
/
http://nopaste.info/72717de3f2.html
Is there anything within the function that I need to change before publishing the Javascript file? I have downloaded the countries file, deleted the functions in there, pasted the above functions exactly, and when I use your sample code for calling the function I get blank drop down menus.
Any further help would be great.
would have to see. Paste ur code to nopaste
Ok here is the code.
http://nopaste.info/c5074a5527.html
That works for me. But
. check ur quotes
CHECK YOUR QUOTES IN YOUR JS FILE….
the quotes in this thread are wonky, re-type your quotes. if you use gedit they should be pink, not black. Now I recall that had me thinking for 20 minutes before i realized some quotes were black
Be Careful if you copy paste from this forum, the quotes will not be the correct onesl
http://nopaste.info/69d346efd4.html
Click the above link, click hide row numbers, and you can copy paste that
Nice work
good job
really helpful
Its running perfectly. but i got a problem at the end of the list i see some scripts getting added as options in the combobox. both in country and state
Using lQuery chosen plugin the script don’t work. Any idea?
Double check ur quotes. If you copy from the comments on this page your quotes are the incorrect characters (not really quotes)
Thanx for the code… i hv fed up on getting code for countries and states dropdpown…. its working, very good and thnx alot
Hi!, only as an observation, in your javascript code you have this:
<script language="javascript"<print_country("country");
there is a tiny mistake with the
it must be:
print_country(“country”);
And now it works!
This script helped me out
thanks
<script language="javascript"<print_country("country");
i am a beginr in html . . this code is very useful i got only error with the script line i'v given above…. i wnt to know –
wht's the use of this line . ..
when i put this line in my code all next input box stopd working, and when i comment this line i am able to select all country and states . .no effects
hai,am using this code its working good but i have an issue am using state countries drop downs 2 times in the same form, for first drop downs its working but second on showing empty drop downs, pls help me to solve this……….
hai,Thanx 4r reply……. and already i solve this issue………….
Hi This code working very without any issue.
Thanks
problem with this line
<script language="javascript"<print_country("country");
Thanks a lot for this script ! I wonder if is possible to add a link to some cities, after choose a city, people go to another page.
Is this possible?
- do you have instruction how to add this script to a wordpress page ?
many thanks
Cristina
its not work