gr3g
gr3g

Reputation: 2914

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:

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

Upvotes: 1

Views: 6666

Answers (4)

Carlos Ortega
Carlos Ortega

Reputation: 1

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

Upvotes: 0

Sodik Abdullaev
Sodik Abdullaev

Reputation: 158

try this if still needs anybody. Quick solution.

$("form").keypress(function(e) {
  //Enter key
   if (e.which == 13) {
   return false;
 }
});

Upvotes: 0

skyline3000
skyline3000

Reputation: 7913

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

Upvotes: 2

Dalorzo
Dalorzo

Reputation: 20024

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.

Upvotes: 4

Related Questions