Ad

Dynamic Dropdown Redirection

- 1 answer

I'm using JS to dynamically populate a select list from the option of another select list. The population is working correctly, however once the second option is picked I want the user to be navigated to the girl URL. What am I missing?

< script type = "text/javascript" >
  function populate(s1, s2) {
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    if (s1.value == "Chevy") {
      var optionArray = ["|", "http://www.example.com|Camaro", "http://www.example.com|Corvette", "impala|Impala"];
    } else if (s1.value == "Dodge") {
      var optionArray = ["|", "http://www.example.com|Avenger", "http://www.example.com|Challenger", "http://www.example.com|Charger"];
    } else if (s1.value == "Ford") {
      var optionArray = ["|", "http://www.example.com|Mustang", "http://www.example.com|Shelby"];
    }
    for (var option in optionArray) {
      var pair = optionArray[option].split("|");
      var newOption = document.createElement("option");
      newOption.value = pair[0];
      newOption.innerHTML = pair[1];
      s2.options.add(newOption);
    }
  }
< /script>
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
  <option value=""></option>
  <option value="Chevy">Chevy</option>
  <option value="Dodge">Dodge</option>
  <option value="Ford">Ford</option>
</select>
<select id="slct2" name="slct2" onchange="form.submit()"></select>

Ad

Answer

Assuming your form looks like this:

<form name='form' id='exampleForm' action='whatever'>...</form>

your onchange event should look like this:

onchange="document.form.submit()"

or

onchange="document.getElementById('exampleForm').submit()"

Alternatively, you don't even need a form. You could do:

onchange="window.location.href='my.url'"

...or put it in a function:

onchange="foo()"

...

function foo() {
    var s2 = document.getElementById('slct2');
    window.location.href = "my.url?model=" + s2.options[s2.selectedIndex].value;
}
Ad
source: stackoverflow.com
Ad