You can use a JavaScript to add all the country names and state names’ Dropdown list. Which is actually done by HTMLand 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. Copy the JavaScript code from the above link and save it in a file “countries.js”
2. Put this code between yourandsection:
<script type= "text/javascript" src = "countries.js"></script>
3. Put this code between yourandsection:
Select Country (with states):   <select id="country" name ="country"></select> Select State: <select name ="state" id ="state"></select> <script language="javascript"> populateCountries("country", "state"); </script>
Please note that, we are using twotags, which are actual drop-down boxes. Here I’ve chosen “country” and “state” as theirID 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="country2" name ="country2"></select> <script language="javascript"> populateCountries("country2"); </script>
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
Great example very useful, although I want to find out if you maybe have the Countries and Regions available for me as a SQL import script. Thanks
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
Bro change the file name “counties2” with “counties”.
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 🙂
I need a city list too. how can i add this? i want like country then state then city….Thanku in advance
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
I want default country start with india ratherthen afghanistan is there any solution for that
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
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 🙂
please , provide me code for country , state and city .
i also want city in third drop down box
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 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 🙂 . check ur quotes 🙂
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");
You need to close the script line;
<print_country("country");
the “print”
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
Thx a lot for the version of the script 3.1 but I think you should edit the original post with the new link, so the people dont get too confused 😀
Please replace North-West Frontier Province to Khyber Pakhtunkhwa
Regards
Yasir Zia
Cell: 00923432490387
I want to change default country as i ndia insted of afghanisthan
How we can make it three level drop down, Like first people select the continent, then country and after that city, please any one have any idea so please let me now, Thanks
I apologize if this is a obvious questions, but how to you add default text to the dropdown. Ex: “select one”
Do you know how you could have two country and state drop downs on one page? When I put a second one, the countries do not show up.
Really nice work. I applied this script to my website. I am now trying to modify the function so that when Canada is selected it changes the “State:” label to “Province:” and the message should also change to “Select a State” or “Select a Province”. Shouldn’t be too complicated. Will post if I have a result. Thank you.
Here it is, worked for me:
if(state_list_index === 239){ // 239 is the index for United States
$(“#country”).prev().prev().prev().html(“State:”);
option_str.options[0] = new Option(‘Select State’, ”);
}else{
$(“#country”).prev().prev().prev().html(“Province/District:”);
option_str.options[0] = new Option(‘Select One’, ”);
}
even better, under the print_state function:
if(state_list_index === 239){ // 239 is the index for United States
$(‘#’+state_id).prev().html(“State:”);
option_str.options[0] = new Option(‘Select State’, ”);
}else{
$(‘#’+state_id).prev(‘label’).html(“Province/District:”);
option_str.options[0] = new Option(‘Select One’, ”);
}
***** please replace in body code syntax error
or replace this
<script language="javascript"<print_country("country");
with
print_country(“country”);
Hi, I am using your project. Very useful.
Though, it doesn’t handle the case where you select a country twice, it will add up the regions from both countries in the Region dropdownlist.
This can be achieve by adding the following to the print_state method after declaring option_str:
option_str.options.length = 0; //in javascript
OR
$(option_str).empty(); //in jquery
Very good code bro,
but if i supposed to show data from db how can i use this.
plese rply if there is any way out
if i want to edit the profile of user then in the country field it shows some number how could i get the country name rather then number….
thanks,
there is an error in point 3. you are giving the wrond javascript function calling syntax in line 5 on the code area.
Hi,
I use this script for classipress and it works perfect untill one point. Country and state are not stored in the database. How can I update mysql with choosen country and state?
Thank this was very useful for my project. after getting this in a drop down menu how to validate using servlets?? I mean in the form
private boolean isValidCountry(String ct) {
if (ct.equals(” “)){
return false;
}
return true;
}
what should be ct equal to in order to validate??Sorry as am a beginner am asking this question.
Is there way to use this countries.js in zf2 . If anybody knows give me hint
hai wat u provided code is very nice easy to select country and automatic up dation of sate i added cities of my country every thing is working in my website as front end but after selecting country and state and city that data is not storing in my sql database i use to call to store in database as cmd.Parameters.AddWithValue(“@con”, country.SelectedValue);
this code is asp.net for storing selected value from dropdownlist to database but its now working please send me rply for this with solution
hai iam saikiran u are not replied for my question i think you didnot understand my question ok let me ask same question in different manner first of thanq for giving such a javascript code for html page.But i used it in asp.net c#. I changed in code select tag into remaining code what u given i kept same its working but after selecting the value from drodownlist the value is not storing into sql database please give me reply soon thanq…. this is my mail id srisai00123@gmail.com
hi this is saikiran i got answer for the above question by using string str=Request.Form[“dropdownlist1”].Tostring(); thanq………
Can you configure the script so that values returns the ISO code of countries, i.e. two alphabets in values! Well also if you can give option to developer to choose between type of value returned from selection, it would be really appreciable.
Hi Saikiran, could you update the code to rename Yugoslovia -> Serbia
I want drop down list ofor cities of india? can anyone help me?
Very nice code. It works perfect. Thanks.
My question is how to pull out states from a db and not from js itself.
Any help apreciated.
hi thanks your code is seriously a time saver but there’s an issue.by using this src my other validations such as alphabet validation, numeric validation are not working… any1 with help plzz…
The jquery.country plugin may helps, is a plugin for country/state/city dropdown without any use of database and server side coding. http://oohm-software.github.io/jquery.country/
thanks 🙂
Modified to accept a default country:
print_country(“country”, “United States”);
function print_country(country_id, default_country){
// 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]);
}
//Set default country and populate states
if(default_country != “”) {
$(“#country”).val(default_country);
print_state(‘state’, country_arr.indexOf(default_country));
}
}
function populateStates(countryElementId, stateElementId) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length = 0; // Fixed by Julian Woods
stateElement.options[0] = new Option(‘Select State’, ‘0’);
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split(“|”);
for (var i = 0; i < state_arr.length; i++) {
stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
}
}
function populateCountries(countryElementId, stateElementId, countrySelected) {
var indexSelected=0, countryElement = document.getElementById(countryElementId);
countryElement.length = 0;
countryElement.options[0] = new Option('Select Country', '0');
countryElement.selectedIndex = 0;
for (var i = 0; i < country_arr.length; i++) {
countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
if(countrySelected && country_arr[i] == countrySelected){
indexSelected = i+1;
}
}
if (stateElementId) {
if(countrySelected){
countryElement.selectedIndex = indexSelected;
populateStates(countryElementId, stateElementId);
}
countryElement.onchange = function () {
populateStates(countryElementId, stateElementId);
};
}
if(countrySelected){
countryElement.selectedIndex = indexSelected;
}
}
Example of Use:
Country:
State:
inside the html script tag you have to write:
populateCountries(“country”, “state”, “India”);
country – the id of country select box
state – the id of state select box
India – the selected country name
It gives the country drop down and state drop down of India. When you want your country name just change the country name which one you want to show on page load. It will automatically load the states of the country you mentioned.
When you want only country drop down, you just make blank the state drop down id.
populateCountries(“country”, “”, “India”);
country – the id of country select box
India – the selected country name
Dear Shafi ul Azam, thumbs up for your work. But I’ve required a form with three different drop downs i.e. country –> State/Province –> City.
Can you please suggest me something helpful in this regard??
the country has to be default selected and also its corresponding state. how do i do it using php and js only
Inside the print_state function I have to add a option_str.innerHTML=””; cuz everytime I change country didn’t erase the last country on the options
Thanks for sharing your script with everyone. Is it possible to include an additional info on the region section like image and hyperlink stuff?
Ie Choose your location > Pulldown with all states listed > choose China
Next image/link appears with region list populated > Shanghai.
Hi, everyone. I have been trying to get the DEFAULT ‘Country’ and ‘STATE’ codes to work, but none of them work!! 😦 I suspect that it becos i have COPIED them from this page and the ” and ‘ symbols have gone crazy. Hmmmm… perhaps even other symbols NOT working properly, Can someone email me the CORRECT working jscript for the Default Country and State? My email is: andrewbsc@gmail.com
Appreciate this much 🙂
God damnit!! Finally I gotten it sorted out, the Default “Country” and “State” issue.
All thanks to the codes that B (camaroqqq) posted. Indeed it is the bloody ” and ‘ being messed up on this stupid webpage 😦
Thank you,… and ANYONE HERE needs the lovely code pls email me: andrewbsc@gmail.com
AND another problem to take note is:
Do not name your js file as ‘countries3-1.js’ IF you are using Chrome! It will not work with the HYPHEN!!! Hyphen in the name works with Firefox, but not Chrome!! Renaming it to ‘countries31.js works beautifully!!
For United States abbreviations, I made the following mods:
Replace s_a[238] with this (Credit BTurner above):
s_a[238]=”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”;
modify print_state() function:
if(state_index == 238) { // United States
for(x in state_arr){
option_str.options[i++] = new Option(state_arr[x].substring(3), state_arr[x].substring(0,2));
}
} else {
for(x in state_arr){
option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
}
}
Hi amulya, How to solve mutiple entry of it in one page
Hi Amulya. how do you solve multiple entry of it in one page. Please help me
pls help to get perfect dropdown relationship of country and state (like india means state should be delhi but not sydney)..currently working on spring and hibernate