需要帮助创建特定脚本

时间:2017-10-31 17:49:33

标签: javascript html forms textbox

寻找一个JavaScript,它从文本框中获取输入,并使用他们的输入将用户定向到URL。

输入ID:_______ SUBMIT

输入“123”并点击“提交”时,它会转到www.mywebsite.com/users/123.html。

2 个答案:

答案 0 :(得分:0)

这样做的一种方法是在提交表单之前创建表单并更改其操作。

(function () {
    var form = document.querySelector("form.js-form");
    if (form instanceof HTMLFormElement) {
        var text = form.querySelector("input[type='text']");
        if (text instanceof HTMLInputElement) {
            form.addEventListener("submit", function (evt) {
                form.action = "www.mywebsite.com/users/" + text.value + ".html";
            });
        }
    }
})();
<form action="javascript:void(0)" method="GET" class="js-form">
  <input type="text" placeholder="Insert a user Id" />
  <input type="submit" value="submit" />
</form>

或者您可以只有一个输入和一个按钮,单击该按钮将重定向窗口。

(function () {
    var text = document.querySelector(".js-text");
    var submit = document.querySelector(".js-button");
    if (text instanceof HTMLInputElement && submit instanceof HTMLButtonElement) {
        submit.addEventListener("click", function (evt) {
            window.location.replace("www.mywebsite.com/users/" + text.value + ".html");
        });
    }
})();
<input type="text" placeholder="Type an Id" class="js-text" />
<button class="js-button">Submit</button>

答案 1 :(得分:0)

<html>
  <body bgcolor="silver">
    <div  class="align-center" >
      <h2> Re-Direction</h2> 
    </div>
    <label>Enter Your Search Interest</label>
    <input type="text" id="data"/></br>
    <!-- input type="text" would help you to create a box which would accept a user value -->
    <div class="align-center"><button onclick="redirection()">Click Me</button></div> 
    <!-- in the above line we attach a JS function redirection to the button -->
  </body>
  <script>
    function redirection(){
      //document.getElementById("data") would search for the html element with id="data" which in our case is input element
      var tempData = document.getElementById("data");
      //window.location.href would help you with redirection to the desired url
      window.location.href = 'https://en.wikipedia.org/wiki/'+tempData.value;
      //window.location.href="your urli.e www.mywebsite.com/users/"+tempData.value;
    }
  </script>
</html>
相关问题