The below code is used to access a webpage I called myPage.html by entering a password of 1234. Once the password is entered the User either clicks the Login Button or presses the "Enter" key.

Clicking the login button works OK. My problem is that I have to press the Enter key twice for it to go to myPage.html

What do I need to change so I only have to press the Enter key once?


function TheLogin() {
var password = '1234';
if (this.document.login.pass.value == password) {
top.location.href="";}
}

</script>
<p align="center">
<p align="center"><br>
<p align="center"><font size="5"><b><font color="#000000">Please enter the Password to Enter</font></b></font><br>
<p>&nbsp; </p>
<center>Enter your password:<br>
<form name="login" style="margin: 0px">


<INPUT TYPE="password" NAME="pass" size="17" onKeyDown="if(event.keyCode==13) event.keyCode=9;" style="width: 152px; margin: 5px;"><br>

<input type="button" value="Click to Login" style="width : 150px; margin: 3px" onClick="TheLogin(this.form)">
</form>
</center>

Dani AI

Generated

The behavior comes from the password field intercepting the Enter key and moving focus instead of submitting. That makes the first Enter only shift focus and a second Enter activate the button. s markup shows an inline key handler on the input that causes this. A cleaner approach is to let the browser handle Enter-to-submit (use a submit control) and perform validation in the form submit handler.

A straightforward pattern that avoids inline key hacks is to give the form an id, use a submit button, and handle the form's submit event. The submit handler can call preventDefault(), validate the password client-side (only for UX), and then redirect when valid. Example pattern:

document.getElementById('loginForm').addEventListener('submit', function(e) {
  e.preventDefault();
  var pw = this.querySelector('input[type="password"]').value;
  if (pw === storedPassword) {
    window.location.href = 'landing.html';
  } else {
    alert('Incorrect password');
  }
});

As noted, changing the button to a submit control simplifies Enter behavior. As warned, client-side-only "logins" are visible to visitors and are not secure; any real authentication must be validated on the server. For modern key handling see the KeyboardEvent.key recommendation on MDN (KeyboardEvent.key), and for form semantics consult MDN form documentation.

Recommended Answers

All 2 Replies

Make '<input type="submit"' instead of '<input type="button"'...

Also why are you doing this login with JavaScript and not PHP?

Remember that a visitor can read your javascript...
not exactly secure, is it/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.