【问题标题】:Javascript / HTML Question: Taking an input value from a form, and using this to send user to a URLJavascript / HTML 问题:从表单中获取输入值,并使用它来将用户发送到 URL
【发布时间】:2021-07-11 01:20:58
【问题描述】:

感谢阅读。我是 Javscript 的新手,并且已经做了很多搜索来尝试解决这个问题......(无济于事)

我正在尝试创建一种用户在表单上输入单个单词的情况。然后,当他们单击提交按钮时,网站会从输入中获取单词,将其附加到不完整 URL 的末尾,然后将它们发送到完整的 URL。

很容易理解为什么这对你们中的一些人不起作用。而且,令人尴尬的是,我认为最好采用完全不同的方法。

感谢您的建议。

<form action="https://vrnaut.neocities.org/"  method="get">
  <label for="MyForm">Enter One Word:</label>
  <input type="text" id= "OneWord" name="OneWord" required>
</form>

<button onclick="myFunction()">Submit</button>

<script>
function myFunction(form) {
  var GoHere = form.OneWord.value;
  location.replace("https://vrnaut.neocities.org/" + GoHere);
}
</script>

【问题讨论】:

  • 你永远不会向myFunction传递任何东西...但是传递给EventListener的唯一参数是EventObject,所以你会想要将该函数包装在另一个函数中并传入代表你的表单的参数.你可以像function myFunction(){ location = 'https://vrnaut.neocities.org'+document.getElementById('OneWord').value.trim(); } 那样做。当然,如果你不想每次点击按钮时都解析 DOM,那么请事先获取 Node,将其分配给一个变量以供重用。
  • 出于同样的原因,内联 style 属性是错误的标记,内联 on* JS 处理程序属性也是错误的。 CSS 和 JS 应该只在一个地方,那就是它们各自的文件或标签。请改用Element.addEventListener()。

标签: javascript html forms url


【解决方案1】:

您的方法非常好。所需要的只是一点点调整。

<form action="https://vrnaut.neocities.org/"  method="get">
  <label for="MyForm">Enter One Word:</label>
  <input type="text" id= "OneWord" name="OneWord" required>
  <button onclick="myFunction(this.parentElement)">Submit</button>
</form>

<script>
function myFunction(form) {
  var GoHere = form.getElementsByTagName("input")[0];
  location.replace("https://vrnaut.neocities.org/" + GoHere.value);
}
</script>

【讨论】:

【解决方案2】:
  • 将按钮放入你形成的
  • 永远不要监听按钮点击 - 而是使用 FORM 的 "submit" 事件:

const EL_form = document.querySelector("#myForm");
const EL_word = document.querySelector("#OneWord");

EL_form.addEventListener("submit", (ev) => {
  ev.preventDefault();
  location.replace(EL_form.action + EL_word.value);
});
<form id="myForm" action="https://vrnaut.neocities.org/" method="get">
  <label for="MyForm">Enter One Word:</label>
  <input type="text" id="OneWord" name="OneWord" required>
  <button type="submit">Submit</button>
</form>

【讨论】:

  • 非常感谢,这非常有效。我会尝试从这个例子中学习。不幸的是,我是这个 stackoverflow 的新手,所以我的赞成票(我已经给你了)被记录下来,但直到我的声望达到 15 分才会出现。
  • @T.ShawnJohnson 你很快就会 15 岁了。快乐的编码
猜你喜欢
  • 1970-01-01
  • 2015-04-22
  • 2019-02-26
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2015-05-12
  • 2017-11-26
  • 1970-01-01
相关资源
最近更新 更多