0

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:

<div id="div"> Only execute javascript on click, not enter key press </div>

JAVASCRIPT:

$("#div").click(function () {

   /* IF ENTER KEY PRESSED, RETURN FALSE */

   $("#div").keypress(
    function(event){
     if (event.which == '13') {
        event.preventDefault();
        alert('clicked');
      }
   });

  /* Div has been clicked, continue code... */

});

This doesn't work...
Maybe there is a better way:

$("#div").MOUSE_CLICK_EVENT(function () {});
Thevs
  • 3,189
  • 2
  • 20
  • 32
gr3g
  • 2,866
  • 5
  • 28
  • 52

4 Answers4

3

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.

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
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();
        return false;
    }
};

document.getElementById('div').onclick = function (evt) {
    // do whatever you want here
};
skyline3000
  • 7,639
  • 2
  • 24
  • 33
0

try this if still needs anybody. Quick solution.

$("form").keypress(function(e) {
  //Enter key
   if (e.which == 13) {
   return false;
 }
});
Sodik Abdullaev
  • 158
  • 4
  • 12
0

Also you need to consider 3 key events: keydown, keypress and keyup.

    $("#ID").keydown (function (e) {
        if ( e.key == 'Enter') {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });

    $("#ID").keyup (function (e) {
        if (e.key  == 'Enter') {
           e.preventDefault();
           e.stopPropagation();
           return false;
        }
    });

    $("#ID").keypress (function (e) {
        if (e.key  == 'Enter') {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });