簡體   English   中英

Javascript / HTML 問題:從表單中獲取輸入值,並使用該值將用戶發送到 URL

[英]Javascript / HTML Question: Taking an input value from a form, and using this to send user to a URL

謝謝閱讀。 我是 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>

你的方法非常好。 所需要的只是一點點調整。

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

  • 將按鈕放在表單內
  • 永遠不要聽按鈕點擊- 而是使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM