繁体   English   中英

仅当单击提交按钮时,选项才应导致 URL

[英]Option should leads to URL only when submit button is clicked

我制作了一个包含两个选项的下拉表单,每个选项都指向不同的 URL。我希望仅当单击提交按钮时,所选选项才会指向其“URL”。 我使用了以下 JS 代码:

function handleFormSubmit() {
 var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
var destination = document.getElementById("destination");
location = destination.options[destination.selectedIndex].value;
});
}

现在,当我单击提交按钮时,它不会导航到optionvalue属性中指定的 url。 (什么都没发生。)

以下是我表格中的 HTML:

`<form action="" method="post">
  <label for="destination">Travelling to:</label>
  <select id="destination" name="destination">
    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
  </select>
  <input type="submit" value="Submit">
 </form>`

只需更改文件中的以下代码。

 function link() { var dropDownVal = document.getElementById('destination').value; window.location = dropDownVal; }
 <form action="" method="post"> <label for="destination">Travelling to:</label> <select id="destination" name="destination"> <option value="https://nstcprep.blogspot.com/">Destination 1</option> <option value="https://nstcprep.blogspot.com/">Destination 2</option> </select> <button type="button" onclick="link();">Submit</button> </form>

让我知道这是否有效。

如果您想在新标签页中打开,只需更改此即可。

window.open(dropDownVal, '_blank');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM