JavaScript Country State List

My two cents on project http://sourceforge.net/projects/countries/

I just added default select

Diff:
function print_country(country_id,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);
}

}

Use:
print_country("country","Brazil");

Project information
http://bdhacker.wordpress.com/2009/11/21/adding-dropdown-country-state-list-dynamically-into-your-html-form-by-javascript/

Enjoy!

Advertisement

4 thoughts on “JavaScript Country State List

  1. I added some code by studying your 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]);
    // console.log(“(x = “+x+”) (i = “+i+”) 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”, “Jakarta”);

  2. Not sure if anyone is still monitoring this chat. First, thanks for the code, it was exactly what I needed. Has anyone modified this code so the selected country / state stays selected on form submit? Currently the selections just revert back to index 0 (all countries). Any insight would be extremely helpful.

    Thanks

Leave a Reply to Timmy Cancel 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 )

Facebook photo

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

Connecting to %s