简体   繁体   English

javascript验证和验证点击或输入

[英]javascript validate and validate on click or enter

I have a login script date validates on clicking the submit button.我有一个登录脚本日期验证单击提交按钮。

 // Below function Executes on click of login button. function validate(){ var password = document.getElementById("passid").value; if ( password == "thisisthepassword"){ window.location = "loggedin.html"; // Redirecting to other page. return false; } }
 <form id="code" method="post"> <div class="form-group"><input class="form-control" type="password" name="passid" id="passid""></div> <div class="form-group"> <button class="btn btn-primary btn-block" type="button" value="Login" id="submit" onclick="validate()" style="border: none;">Login</button></div> </form>

Now I want this script to also run when the enter key is pressed after entering the code, but none of the examples I find seems to work in combination with what I already have现在我希望这个脚本也能在输入代码后按下回车键时运行,但我发现的所有示例似乎都无法与我已有的示例结合使用

我想,您可以更改要提交的按钮类型,并在表单元素上使用 onsubmit="validate()" 事件而不是您在按钮上使用的 onclick 事件

See the snippet below, I've added an event listener that will trigger a button click when enter is pressed.请参阅下面的代码段,我添加了一个事件侦听器,该侦听器将在按下 Enter 时触发按钮单击。 This will still run the same validation that occurs when you click the button.这仍将运行与单击按钮时相同的验证。

 function validate() { var password = document.getElementById("passid").value; if (password == "thisisthepassword") { window.location = "loggedin.html"; // Redirecting to other page. return false; } } //This code will trigger a button click when "enter" is pressed. var input = document.getElementById("passid"); input.addEventListener("keyup", function(event) { // keyCode 13 is the "Enter" key on the keyboard if (event.keyCode === 13) { // Prevent default action event.preventDefault(); // Trigger the button element with a click document.getElementById("submit").click(); } });
 <form id="code" method="post"> <div class="form-group"> <input class="form-control" type="password" name="passid" id="passid" "></div> <div class="form-group "> <button class="btn btn-primary btn-block " type="button " value="Login " id="submit " onclick="validate() " style="border: none; ">Login</button></div> </form>

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

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