Add Dropdown Country & State List Dynamically into HTML form by Javascript


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!

Check the code live here

How to use?

1.  Download and save as countries.js

2. Put this code between your <HEAD> and </HEAD> section:

<script type= "text/javascript" src = "countries.js"></script>

3. Put this code between your <BODY> and </BODY> section:

 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 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="country2" name ="country2"></select>
<script language="javascript">
populateCountries("country2");
 </script>
About these ads

ReMo at Mozilla Reps, open-source enthusiast.

Tagged with: , , , , , , , , , , , , , ,
Posted in JavaScript
130 comments on “Add Dropdown Country & State List Dynamically into HTML form by Javascript
  1. Paola Rozo says:

    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?

  2. aglan says:

    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?

  3. Julian Woods says:

    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

  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. Glen says:

    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. Glen says:

    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. Glen says:

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

    Regards
    Glen

  8. mark says:

    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. Greg says:

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

    • Glen says:

      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. Jan Souza says:

    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
    */

  11. Prabu says:

    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

  12. Ross says:

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

  13. Shafiul Azam says:

    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 :)

  14. amp says:

    Czeck Republic should be Czech Republic

  15. amp says:

    For a list of districts in New Zealand try: http://www.statoids.com/ynz.html

  16. Rok says:

    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.

  17. Andy says:

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

    • Andy says:

      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

  18. Jonathan says:

    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.

  19. engiguide says:

    amazing one… ll help for my website form

  20. Sena Ilic says:

    Terrific submit man. For those who are enthusiastic about Cura de slabire evening me.

  21. DJ says:

    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.

  22. mernslors says:

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

    Great Community, respect all!

  23. Rojan says:

    thank you…

  24. ram says:

    hi i tried to use it with jquery.jqtransform.js it doesn’t work.

  25. Thas says:

    very Good Script .thank you………

  26. ganapathi says:

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

  27. rlearning says:

    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.

  28. ilesh says:

    thankx for this and it’s a good script

  29. melvin says:

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

  30. Sonny says:

    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!

  31. Mitul says:

    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.

  32. Naresh says:

    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

  33. Shalli says:

    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

  34. beginner says:

    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

  35. Denny Morgan says:

    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.

  36. Thanveer says:

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

  37. Aneeq says:

    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

  38. BTurner says:

    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.

  39. BTurner says:

    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.

  40. shivarajrh says:

    Can you send the code to generate country code like for India == 91 like this please i need it for my blog.

  41. Luis says:

    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.

    • Shafiul Azam says:

      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.

      • luis says:

        Hey thanks for the reply.

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

      • Luis says:

        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

  42. jatin says:

    Hi,
    How can i include this in Contact Form 7 for WordPress??
    Thanx in advance

  43. Neetesh says:

    Hi Nice code . Please provide city code too.

  44. Julius Ramos says:

    Thank you for your valuable script, and the great efforts in the research of the countries. You are king!

  45. Julius Ramos says:

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

  46. shaheen says:

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

  47. raghu vikas singh says:

    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.

  48. akshaya says:

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

    • tc says:

      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 :)

    • tc says:

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

  49. tc says:

    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 :)

  50. khoo says:

    Thanks for the code and explanation!! Appreciate it very much =)

  51. Thanks so much, rly help

  52. Rajee says:

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

  53. nunenuh says:

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

  54. Jeff says:

    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.

  55. Greg Marriott says:

    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?

  56. pandi says:

    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

  57. B says:

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

    • JMER says:

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

      Thanks

      • B says:

        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.

      • B says:

        lol that did not paste gracefully. See it here

        http://nopaste.info/eeebfb1f16.html

    • JMER says:

      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?

      • B says:

        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?

    • JMER says:

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

    • JMER says:

      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.

      • B says:

        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 :)

    • B says:

      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

  58. dhiraj says:

    good job
    really helpful

  59. Kartik says:

    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

  60. fran says:

    Using lQuery chosen plugin the script don’t work. Any idea?

    • B says:

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

  61. Kalyan says:

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

  62. Roberto says:

    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! :D

  63. This script helped me out :) thanks

  64. Navneet says:

    <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

  65. amulya says:

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

  66. amulya says:

    hai,Thanx 4r reply……. and already i solve this issue………….

  67. sandeep says:

    Hi This code working very without any issue.
    Thanks

  68. uday says:

    problem with this line

    <script language="javascript"<print_country("country");

  69. cristina says:

    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

  70. palkesh says:

    its not work

  71. 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 :D

  72. Yasir Zia says:

    Please replace North-West Frontier Province to Khyber Pakhtunkhwa
    Regards

    Yasir Zia
    Cell: 00923432490387

  73. Nainesh says:

    I want to change default country as i ndia insted of afghanisthan

  74. Aadil Afzal says:

    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

  75. I apologize if this is a obvious questions, but how to you add default text to the dropdown. Ex: “select one”

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

  77. Diego says:

    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.

    • Diego says:

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

      • Diego says:

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

  78. Sanjay aagarwal says:

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

  79. Blacksheep5555 says:

    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

  80. Rahul Singh says:

    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

  81. rakesh says:

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

  82. rehan says:

    thanks,

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

  83. John says:

    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?

  84. Theju says:

    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.

  85. zend newbie says:

    Is there way to use this countries.js in zf2 . If anybody knows give me hint

  86. saikiran says:

    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

  87. saikiran says:

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

To keep the Web Open
Web docs by developers, for developers on MDN Work <span>for</span> Mozilla
Firefox OS
Thanks for visiting my blog!
  • 481,909 hits from Aug, 2009
Follow

Get every new post delivered to your Inbox.