iJade
iJade

Reputation: 23791

JavaScript function getting called twice on Enter key press

I have a button in my html page

<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />

I have binded a jquery click event to this button like

 $('#btnLogin').click(function () {
    ValidateLogin();
});

I'm also checking the enter key press to call the same function ValidateLogin(); like below

$(document).keypress(function (e) {
    if (e.which == 13) {
        ValidateLogin();
    }
});

The issue that i'm facing is when the user presses the tab key to get in focus over the Login button and then press Enter Key the ValidateLogin() is called twice.How to deal with this situation.

Note : i can't use type="submit" to do a form submit ..since i'm using ajax call on button click

Upvotes: 3

Views: 6563

Answers (3)

msapkal
msapkal

Reputation: 8346

Since it's a form I would prefer to attach event on form elements instead on document.

Use form element like text, textarea etc. on click of enter should submit the form.

$('input:text, textarea').keypress(function (e) {
    if (e.which == 13) {
        ValidateLogin();
    }
});

In your case event is bubbled from the button to document hence it is called twice.

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78525

You should use the submit event instead. Your browser is probably firing the click event when pressing enter and that is effectively the same as pressing the submit button:

$("form").submit(function(e) {
    // Stop the form submitting
    e.preventDefault(); 
    ValidateLogin();
});

function ValidateLogin() {
    $.ajax({
        // ...
    }).done(function(e) {
        if(!e.valid) {
            alert("Invalid Login");
        }
    });
}

Second reason, even if your keypress was to work correctly, I can press a button by pressing spacebar too.

Here is a full Fiddle to demonstrate.

Upvotes: 2

Manoj Pilania
Manoj Pilania

Reputation: 666

Its working fine check this fiddler DEMO

      <input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />

  $('#btnLogin').click(function () {
      //ValidateLogin();
      alert('click');
  });
  $(document).keypress(function (e) {
      if (e.which == 13) {
          //ValidateLogin();
          alert('enter');
      }
      e.preventDefault();
  });

Upvotes: 0

Related Questions