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!

Check the code live here

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>

154 thoughts on “Add Dropdown Country & State List Dynamically into HTML form by Javascript

  1. 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?

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

  2. 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?

    1. Great if you only want US, Canada, UK and a VERY FEW other country states/provinces! Otherwise absolutely USELESS

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

      1. I need a city list too. how can i add this? i want like country then state then city….Thanku in advance

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

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

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

  7. Bits got stripped out of my message. If you can help, please eMail me and I will give the full code.

    Regards
    Glen

    1. I want default country start with india ratherthen afghanistan is there any solution for that

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

  9. 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)?

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

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

  11. 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){

    1. please , provide me code for country , state and city .
      i also want city in third drop down box

  12. 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!!

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

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

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

  15. Hello all! I like this forum, i organize many inviting people on this forum.!!!

    Great Community, respect all!

  16. just intimate print error on display instead this print_country(“country”);
    our code is <script language="javascript"<print_country("country");
    its wonder

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

  18. 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 =(

  19. 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!

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

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

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

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

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

  25. 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….

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

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

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

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

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

      1. Hey thanks for the reply.

        Kind just tested on a HTML page and it is giving the same error message when debugging.

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

  30. 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;
    }

  31. Hi, i hv used ur code but it doesn’t display the country list,state ?? I followed your instructions.
    Plz help..

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

  33. 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”);

    1. 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 🙂

    2. 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".

  34. 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 🙂

  35. Thanks for your coding. I found ur coding very helpful. i request for cities as state is selected. will i get that coding

  36. 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”);

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

  38. 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?

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

  40. 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);
    }
    }

    1. B this is great but I’m new to JS and was wondering where I designate the default Country and State.

      Thanks

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

    2. 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?

      1. 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?

    3. 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”);

      1. Sorry just realized the code didn’t paste well.

        /
        /
        /Country
        /
        /
        /
        /

        /
        /State
        /
        /
        /
        /print_country(“country”, “US”, “NY”);
        /
        /

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

      1. 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 🙂

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

    1. Double check ur quotes. If you copy from the comments on this page your quotes are the incorrect characters (not really quotes)

  42. Thanx for the code… i hv fed up on getting code for countries and states dropdpown…. its working, very good and thnx alot

  43. 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! 😀

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

  45. 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……….

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

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

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

    1. 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’, ”);
      }

      1. 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’, ”);
        }

  49. ***** please replace in body code syntax error
    or replace this
    <script language="javascript"<print_country("country");
    with
    print_country(“country”);

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

  51. 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….

  52. thanks,

    there is an error in point 3. you are giving the wrond javascript function calling syntax in line 5 on the code area.

  53. 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?

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

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

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

    1. hi this is saikiran i got answer for the above question by using string str=Request.Form[“dropdownlist1”].Tostring(); thanq………

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

  58. 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…

  59. 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));
    }
    }

  60. 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;
    }
    }

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

  61. 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??

  62. the country has to be default selected and also its corresponding state. how do i do it using php and js only

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

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

  65. 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 🙂

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

  67. 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!!

  68. 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]);
    }
    }

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

Comments are closed.