重定向选择选择输入

时间:2016-11-14 04:43:19

标签: javascript html

 <script type="text/javascript">
  var x = document.getElementById("mySelect").value;
</script>

<form action="something?val="+x enctype="multipart/form-data" method="post">
     <label>Select the Playlist:</label>
     <select name="select" id="mySelect">
      <option value="#">----Select-----</option>
      <option value="playlist1">Playlist1</option>
      <option value="playlist2">Playlist2</option>
     </select>
     <input type="submit">
</form>

现在我希望当我选择播放列表1并按下提交按钮时,我的页面应该重定向到某个东西?val = playlist1 ..但是它重定向到某个东西?val = ..x的值没有被打印到那里。我不能找到错误请帮忙。

3 个答案:

答案 0 :(得分:1)

为您的表单分配ID,以便更容易通过js访问,例如:

...
<form id="myform" action="something" enctype="multipart/form-data" method="post">
...

并使用select元素的change事件处理程序来更改表单的操作,例如:

var selectEle = document.getElementById("mySelect");
selectEle.onchange = function(event) {
    var selValue = event.target.value,  
    frm = document.getElementById("myform");
    frm.action = (selValue != "#") ? "something?val=" + selValue : "something";
}

答案 1 :(得分:0)

var x = document.getElementById("mySelect").value;

//works just like a link
window.location.href = "/somewhere?x=" + x;

答案 2 :(得分:0)

我正在向您解释代码的工作流程:

一旦页面加载后续行将运行(我假设你在标题中写下你的js).at那时你的表单没有呈现,所以x的值是未定义的,

    <script type="text/javascript">
      var x = document.getElementById("mySelect").value;
// this is not going to call automatically , when you change value of select box.
    </script>

一旦您的表单呈现并且您更改了选择框的值,您需要调用一个函数来执行上面的js代码以获得新值。

和其他问题是你在html中使用x的方式,x是一个javascript变量,所以它只能在标签内使用。

<form action="something?val="+x enctype="multipart/form-data" method="post">

对于您的预期结果,不需要javascript简单的html表单就可以做到这一点,使用get形式的方法将输入名称的值自动添加到url中

<form action="something" method="get">
     <label>Select the Playlist:</label>
     <select name="val" id="mySelect">
      <option value="#">----Select-----</option>
      <option value="playlist1">Playlist1</option>
      <option value="playlist2">Playlist2</option>
     </select>
     <input type="submit">
</form>