Stop keypress event

Viewed 111834

How to stop keypress event in keydown.

I have a keydown handler in that I need to stop keypress event.

Actually I have a form and textbox in it.

When user press enter key, keydown is triggering the event and having the handler.

Form submit will triggered be in keypress, so I need to stop the keypress event in my keydown handler.

7 Answers

Here I stopped the event bubbling for up/dn/left/right keys:

    $(document).on("keydown", function(e) {
        if(e.keyCode >= 37 && e.keyCode <= 40) {
            e.stopImmediatePropagation();
            return;
        }
    });

I also tried e.preventDefault or event.cancelBubble = true from the answers above, but they had no impact.

I was able to get the event.preventDefault(); to work in Safari and Firefox, but not IE7 or IE8.

If you only want to disable the enter key, make sure that you're also checking for the key value (13 for Enter) and only setting event.preventDefault() for that key.

Anyone able to come up with an answer for IE7/8 or Opera?

<input type="text" name="date" id="date" class="form-control select-calender" placeholder="Choose Date" value="" required >

$(document).on('keypress','#date',function(e){
  e.preventDefault();
}); 
Related