2

When you press enter on the keyboard, a form is sent automatically. I wish this were not the case only if a specific field (#myText) has focus when you press enter.

Thanks to this, I have this code now:

$('#myText').on('focusin', function() {
    console.log('focusin');

    $(window).keydown(function(event){
        if(event.keyCode == 13) {
            console.log('enter!');
            event.preventDefault();
            return false;
        }
    });
});

But it doesn't work well, because when the field loses the focus, pressing enter nothing happens.

Where am I wrong?

Mirko Pagliai
  • 1,220
  • 1
  • 19
  • 36

1 Answers1

3

You aren't binding your keydown event to the specific input. Change this line:

$(window).keydown(function(event){

to this:

$(this).off('keydown').keydown(function(event){

JSFiddle demo

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
  • 1
    Everytime input#myText gets focus a new event handler will get created. Change your code to: `$(this).off('keydown').keydown(function(event){` – Taleeb Oct 05 '15 at 16:40