Reputation: 4051
I have a TextBox and I make a AJAX request when the user presses the Enter key.
$('#TextBox1').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
// ajax request
}
});
How can I make it that this event fires only the first time the user presses the enter key?
Upvotes: 2
Views: 9701
Reputation: 1
I had fallen in kinda similar problem. The below code works for me btw.
var executed = false;
$(document).on("keydown", function () {
if (executed === false) {
executeForOnce();
executed = true;
}
});
Upvotes: -2
Reputation: 1
i had the same problem and solved through below code.... and its working fine. I hope this code will also help you.
var EnterKeyPressed = false;
$('#TextBox1').keypress(
function (e) {
if (e.keyCode == 13 && EnterKeyPressed == false) {
EnterKeyPressed = true;
return true;
}
if (e.keyCode == 13 && EnterKeyPressed == true) {
return false;
}
});
Upvotes: 0
Reputation: 207901
Use jQuery's .one()
function.
$('#TextBox1').one('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
// ajax request
}
});
.one()
is like .on()
but it's only executed once.
Try:
var foo = false;
$('#TextBox1').on('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 &! foo) {
e.preventDefault();
console.log("pressed");
foo = true;
}
});
Upvotes: 6