Home > Back-end >  How can I call a function when I press the enter key?
How can I call a function when I press the enter key?

Time:12-03

I'm making a password thing for my website. How can I check if the password is correct by pressing the enter key instead of pressing the submit button? Help would be appreciated.

<html>
 <script>
  function checkPassword() {
   var password = document.getElementById("passwordBox");
   var passwordText = password.value;
   if(passwordText == "password") {
    alert("you got it right");
    return true;
   }
   alert("you got it wrong");
   return false;
   }
   
 </script>
</head>
<body>
 <p style="font-size: 30pt;">something</p>
 <p>Please enter the password to uh... something </p>
 <p>Password: <input id="passwordBox" type="password"/></p>
 <button onclick="return checkPassword();">
    Submit
 </button>
</html>

CodePudding user response:

wrap you input and button in <form> tag and use submit listener you don't need to write onclick and enter click one by one, it will be big mess up in code, on button element ise type="submit" which means it is part of form and it will execute the function if you will click enter or button, I also removed return true and false because it doesn't make any sense in code also read about what is e.preventDefult()

const passInput = document.getElementById("passwordBox")
const form = document.getElementById("form")

form.addEventListener("submit", (e) => {
  e.preventDefault()

   var passwordText = passInput.value;
   if(passwordText == "password") {
    alert("you got it right");
   }else alert("you got it wrong");
})
<p style="font-size: 30pt;">something</p>
<p>Please enter the password to uh... something </p>

<form id="form">
  <p>Password: <input id="passwordBox" type="password" /></p>
  <button type="submit">Submit</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The simplest way to handle enter key press is wrapping it inside a form and setting the onSubmit on the form and type="submit" on the button.

Here is the example.

<html>
    <head>
        <script>
        function checkPassword() {
            var password = document.getElementById("passwordBox");
            var passwordText = password.value;
            if (passwordText == "password") {
            alert("you got it right");
            return true;
            }
            alert("you got it wrong");
            return false;
        }
        </script>
    </head>
    <body>
        <p style="font-size: 30pt">something</p>
        <p>Please enter the password to uh... something</p>

        <form onsubmit="checkPassword()">
        <p>Password: <input id="passwordBox" type="password" /></p>
        <button type="submit">Submit</button>
        </form>
    </body>
</html>
  • Related