Skip to content Skip to sidebar Skip to footer

Javascript Avoid Enter Key Press

I'm trying to detect an Enter key press event when a button has been clicked. I'm new in javascript and don't know the good way to go... HTML:
Only execute jav

Solution 1:

You need to stopPropagation like:

$('#div').keydown(function(event){
  if (event.which == '13') {
    event.preventDefault();
    event.stopPropagation();
  }
});

stopPropagation: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Solution 2:

As others have noted, you need stopPropagation in addition to preventDefault, and you should be listening for the keydown event rather than keypress.

The pure JavaScript way to do this is:

document.getElementById('div').onkeydown = function (evt) {
    if (evt.which === 13) {
        evt.preventDefault();
        evt.stopPropagation();
        returnfalse;
    }
};

document.getElementById('div').onclick = function (evt) {
    // do whatever you want here
};

Solution 3:

try this if still needs anybody. Quick solution.

$("form").keypress(function(e) {
  //Enter keyif (e.which == 13) {
   returnfalse;
 }
});

Post a Comment for "Javascript Avoid Enter Key Press"