1

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>

2
  • Are you limited to vanilla javascript? Commented Jan 8, 2016 at 0:36
  • Are your <select></select>s wrapped in a <form></form> element? Commented Jan 8, 2016 at 0:44

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.