enb081
enb081

Reputation: 4051

Jquery - Event on enter key press only the first time in a TextBox

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?

JSFIDDLE

Upvotes: 2

Views: 9701

Answers (3)

Md Fokrul Hasan
Md Fokrul Hasan

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

Vishal Srivastava
Vishal Srivastava

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

j08691
j08691

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.

jsFiddle example

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;
    }
});

jsFiddle example

Upvotes: 6

Related Questions