简体   繁体   English

html按钮重定向到中指定的页面<input>

[英]html button redirect to page specified in <input>

I need to redirect the user to a page specificed in an input tag. 我需要将用户重定向到输入标签中特定的页面。

<div id="center">
      <input type="text" id="username" placeholder="Username">
      <button onclick="location.href='rooms/VALUE'" id="connect">EnterRoom</button>
</div>

So where it says "VALUE" inside of the button tag, it would redirect to mysite.com/rooms/VALUE 因此,在按钮标记内显示“ VALUE”的位置,它将重定向到mysite.com/rooms/VALUE

the "VALUE" input would be inputted by the user inside the input tag. 用户将在输入标签内输入“ VALUE”输入。

Any simple way I can do this? 有什么简单的方法可以做到吗?

You can get the value of the input using 您可以使用获得输入的值

document.getElementById('username').value

 <div id="center"> <input type="text" id="username" placeholder="Username"> <button onclick="location.href='rooms/' + document.getElementById('username').value" id="connect">EnterRoom</button> </div> 

If you are using jQuery then; 如果您使用的是jQuery,那么;

<button onclick="location.href='rooms/' + $('#username').val() " id="connect">EnterRoom</button>

and with the javascript 并使用javascript

<button onclick="location.href='rooms/' + document.getElementById('username').value " id="connect">EnterRoom</button>

Here is a version with script separated from HTML of what you want. 这是脚本与所需HTML分开的版本。

<div id="center">
      <input type="text" id="username" placeholder="Username">
      <button id="connect">EnterRoom</button>
</div>

<script type="text/javascript">
  var value = ""

  var username = document.getElementById("username")

  username.addEventListener('change', function (e) {
    value = e.target.value
    console.log(value)
  })

  var connect =  document.getElementById("connect")

  connect.addEventListener('click', function (e) {
    location.href='rooms/'+value
  })

</script>

您可以在按钮标记中使用document.getElementById()

onclick="location.href='rooms/' + document.getElementById('username').value"

Its good to have a separate javascript function to do redirect task. 拥有一个单独的javascript函数来执行重定向任务是一件好事。 In your HTML add onclick event for the button and in javascript function write code to validate and redirect. 在HTML中为按钮添加onclick事件,并在javascript函数中编写代码以进行验证和重定向。

HTML HTML

<button onclick="toRedirect()" id="connect">EnterRoom</button>

Javascript 使用Javascript

<script type="text/javascript">
function toRedirect(){
    // get the user input
    var user_value = document.getElementById('username').value ;
    // check the validation
    if(user_value!=''){
        // redirect
       location.href='rooms/' + user_value;
    }else{
        // alert error message
        alert("validation error");
    }
}
</script>

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

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