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!
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”);
doesn’t work!
It’s not work
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