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

5
  • 2
    Just use properties: not variables. Commented Dec 19, 2013 at 10:52
  • @user2864740 can you please elaborate? Commented Dec 19, 2013 at 10:52
  • 1
    you could create a multidimensional array/object. Commented Dec 19, 2013 at 10:53
  • stackoverflow.com/questions/5613834/… Commented Dec 19, 2013 at 11:00
  • @wkaha That answer can works for him, but will be very ugly, ou have to agree. Not even mine's is the best way. OP should do a refactoring on he's code. Commented Dec 19, 2013 at 11:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

will check it and let you know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.