如何在html中按enter键时调用javascript函数

How to call javascript function on pressing enter in html

本文关键字:调用 javascript 函数 enter html 中按      更新时间:2023-09-26

我刚刚开始学习javascript和html,我有一个带有按钮的表单来检查输入的密码是否正确。

然而,我想这样做,当我按下输入时,密码会被检查,而不必按下按钮。

这是html:

<html>
<head>
<script type="text/javascript" src="login.js"></script>
</head>
<body>
<form>
password: <input type="password" name="password" />
<input type="button" value="Enter" onclick="check(this.form)" />
</form>
</body>
</html>

这是我的javascript:

function check(form){
    var test = form.password.value;
    if(test == "password"){
        alert("correct");
    }
    else{
        alert("Incorrect");
    }
}

如果能为我的问题提供任何帮助或建议,我们将不胜感激。感谢

$(document).keypress(function(e) {
    if(e.which == 13) {  //13 is enter key code
       check(form);  //pass form...call function
    }
});

您还可以使用"提交"按钮并覆盖form.onsubmit事件来处理此问题。这样,您只会在表单或任何输入字段上捕获Enter,而不会在整个文档上捕获。

EDIT-示例

上面的例子增强了:

<!DOCTYPE html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="demo_form.asp" onsubmit="return myFunction(this)">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script>
    function myFunction(form) {
        alert(form.fname.value);
        return false;
    }
</script>
</body>
</html>

注:

  1. 请看,我现在执行onsubmit="return myFunction(this)"以返回myFunction()返回的值
  2. 如果myFunction()返回false,则取消提交(不发生),如果返回true,则提交表单