【问题标题】:HTML language and formsHTML 语言和表单
【发布时间】:2020-10-17 19:29:41
【问题描述】:

我的 HTML 表单有问题。我想让网站访问者选择一个地方,然后选择西西里岛的两个地方之一会将他重定向到一个特定的网页,根据选择的地方一个与另一个不同(并且暂时 2 个重定向文件在与主文件相同的文件夹,分别是“Book=Catania”和“Book=Mondello”)。

我使用了<input type = "text"> 和一些“列表”建议。对于答案,我使用了带有 if 条件的 JavaScript 脚本。

<html>
<head>
...
</head>
<body>
<SCRIPT LANGUAGE = "JavaScript">
function checkCheckBox (f) {
if (f.mondello.checked == true)
{
window.location.href = 'book=mondello.html';
return false;
}
if (f.catania.checked == true)
{
window.location.href = 'book=catania.html';
return false;
}}
</script>
<form action = "" method = "POST" onsubmit = "return checkCheckBox (this)">
<fieldset>
<br/>
<legend> Indicates the place </legend>
<input type = "text" size = "40" list = "places">
<datalist id = "places">
  <option value = "Mondello, PA, Sicily" name = "mondello">
  <option value = "Catania, CT, Sicily" name = "catania">
</datalist>
</body>
</html>

【问题讨论】:

  • book=catania.html。那不是 URL...尝试做 ./book=catania.html 。尽管在 URL 中包含 = 对我来说并不合适,除非在查询参数中。
  • onchange事件监听器添加到数据列表或选择列表中,设置值选项属性以匹配您的重定向文件,然后您只需获取所选选项的值即可转发。

标签: javascript html list forms option


【解决方案1】:

按照应有的方式使用表单。

您有很多实际上没有帮助的代码。通过使用基于文本的选择下拉菜单,您实际上可以在该字段中输入您想要的任何内容。这可能会导致您的网站出现 404。

我已将您的输入更改为带有姓名簿的选择。在堆栈 sn-ps 中很难显示,但是当它提交表单时,它将使用参数book=&lt;selected option&gt; 导航到当前页面(更改在表单元素上添加操作)。您可以添加回 post 方法,该方法会将其从 URL 中隐藏,但这会使链接到朋友变得困难。

您需要的唯一 JS 是强制表单在选择更改时提交。您需要使选择器更适合您的场景,否则这就是 JS 所需要的全部内容。

document.querySelector('select').addEventListener('change', function() {
  document.querySelector('form').submit();
})
<body>
  <form>
    <select name="book">
      <option disabled selected>Select one</option>
      <option value="mondello">Mondello, PA, Sicily</option>
      <option value="catania">Catania, CT, Sicily</option>
    </select>
  </form>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2011-02-23
    • 2015-03-20
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多