0

I'm trying to do a small thing in which when the user selects a country in one drop down it should show the corresponding states in another drop down.

For example, My country array is

var country_list = ["Afghanistan","Albania","Algeria","Andorra","India"];

and the country's state array is something like

var Algeria=["state1", "state2", "state3"];
var Albania=["state1", "state2", "state3"];
var India=["Andaman Nicobar", "Andhra Pradesh", "Arunachal Pradesh"];
var Afghanistan=["state1", "state2", "state3"];

I load the countries by

for(var i=0;i< country_list.length; i++)
{
$('.country_select').append('<option 
value='+country_list[i]+'>'+country_list[i]+'</option>');
}

and, when the user selects India it should load all the Indian states. I'm using switch case like

case "India":
for(var i=0;i< India.length; i++)
{
$('.state_details').append('<option value='+India[i]+'>'+India[i]+'</option>');
}

The code works fine. Now, If I want to add another country's state then I've to add another switch case. I've totally 206 Countries in the country_list array. So If I want to add the 206 country's state, do I need to write 206 switch cases for every country? Or is there any simple methods to make the variable value as another variable in javascript? If so, then I can call the array by the selected value in the country list.

I hope you understand my question. Thanks in advance

Linga
  • 10,379
  • 10
  • 52
  • 104

1 Answers1

4

You can create an object of states like this:

var States = {
    Algeria: ["state1", "state2", "state3"],
    Albania: ["state1", "state2", "state3"],
    India: ["Andaman Nicobar", "Andhra Pradesh", "Arunachal Pradesh"],
    Afghanistan: ["state1", "state2", "state3"]
}

Then you can use like this:

var States = State[Selected_State];
for(var i=0;i< States.length; i++)
{
    $('.state_details').append('<option value='+States[i]+'>'+States[i]+'</option>');
}

Considering Selected_State is the string with the state, like India.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105