简体   繁体   中英

How to call javascript function on pressing enter in html

I've just started learning javascript and html and I have a form with a button to check whether the password that has been inputted is correct.

However, I want to make it so that when I press enter the password is checked instead of having to press the button.

Here's the 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>

Here's my javascript:

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

Any help on my problem or any advice at all would be greatly appreciated. Thanks

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

You can also use a "submit" button and override the form.onsubmit event to handle this. That way you only capture the Enter on the form or any input fields and not on the whole document.

EDIT - Example

The above example enhanced:

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

Notes:

  1. See that I now do onsubmit="return myFunction(this)" to return the value that myFunction() returns
  2. If myFunction() returns false the submit is canceled (not happening), if it returns true the form is submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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