动态下拉重定向

时间:2016-01-08 00:28:13

标签: javascript

我正在使用JS从另一个选择列表的选项中动态填充选择列表。人口正常工作,但是一旦选择了第二个选项,我希望用户被导航到女孩URL。我错过了什么?

< 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>

1 个答案:

答案 0 :(得分:1)

假设您的表单如下:

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

您的onchange事件应如下所示:

onchange="document.form.submit()"

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

或者,您甚至不需要表格。你可以这样做:

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

......或者把它放在一个函数中:

onchange="foo()"

...

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