Change dropdown list based on selection of a different dropdown list.

Discussion in 'JavaScript' started by dot_t, Oct 4, 2006.

  1. #1
    I have a dropdown list of countries. When one is selected, I need the list of states or provences from that selected country to populate the next dropdown or a text field to be displayed so one can enter a 'region'. I also need to pass the selected country and state or region on to a database.

    I am not very familiar with javascript, but I understand there is a way to this using javascript.

    Thanks for any and all help!
     
    dot_t, Oct 4, 2006 IP
  2. frankcow

    frankcow Well-Known Member

    Messages:
    4,859
    Likes Received:
    265
    Best Answers:
    0
    Trophy Points:
    180
  3. dot_t

    dot_t Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hey - Thanks for the direction!! I found a little easier code that is working great:

    function countryDDChange(c,s){

    var evt = document.getElementById(c);

    var selectedIndex = evt.selectedIndex;
    //var targetDD = document.getElementById("regionDD")
    var targetDD = document.getElementById(s)
    while(targetDD.length > 0){
    targetDD.remove(0);
    }

    if(evt.options[selectedIndex].value == "Mexico"){

    var newElement = document.createElement("option");
    newElement.text = "Aguascalientes";
    newElement.value = "Aguascalientes";
    targetDD.options.add(newElement);
    }else if(evt.options[selectedIndex].value == "Latin America"){
    var newElement = document.createElement("option");
    newElement.text = "Columbia";
    newElement.value = "Columbia";
    targetDD.options.add(newElement);

    }
    }

    Then i call it from the dropdown box:
    <select name="projectCountry" class="textBox" id="projectCountry" size="1" onChange="countryDDChange('projectCountry','projectState')">

    And the dropdown box named 'projectState' is supplied with the states from Mexico or Latin America.

    Thanks for your help. I hope this helps others.
     
    dot_t, Oct 5, 2006 IP
  4. frankcow

    frankcow Well-Known Member

    Messages:
    4,859
    Likes Received:
    265
    Best Answers:
    0
    Trophy Points:
    180
    #4
    the problem with that code is that you're hard-coding each option. It's much more maintainable, as well as more efficient to do it with the code I sent, that stores all potential options in arrays
     
    frankcow, Oct 5, 2006 IP
  5. dot_t

    dot_t Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I bet you are right!!

    But like I said, i am a newbie and this works for now. I have a gut feeling the client will want to add all countries of the world and then I will be very grateful for your code.

    Wish me luck.
     
    dot_t, Oct 5, 2006 IP