Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  109] [ 4]  / answers: 1 / hits: 6001  / 11 Years ago, wed, january 8, 2014, 12:00:00

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


More From » jquery

 Answers
7

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.


[#48900] Tuesday, January 7, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coleman

Total Points: 518
Total Questions: 81
Total Answers: 96

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
;