37
votes

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

7 Answers

59
votes
function onKeyDown(event) {   
  event.preventDefault();
}

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault

or

function onsubmit(event) {
  return false;
}

return false to stop events propagation

4
votes

In opera, you have to use the keypress event to prevent the default actions for keyboard events. keydown works to prevent default action in all browsers but not in opera.

See this long list of inconsistencies in keyboard handling across browsers.

4
votes

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.

1
votes

Write,

    <script type="text/javascript">
      function keyDn(obj)
      {
        if(window["event"]["keyCode"]==48)  // key 0 will disabled keyPress event
         {
           obj["onkeypress"]=null;
          }
       }
      function keyPs(obj)
      {
        alert("Keypress");
      }

    </script>

  <form id="form1" runat="server">
    <div>
     <input type="text" onkeydown="keyDn(this)" onkeypress="keyPs(this)" />
    </div>
  </form>

in keydown handler.

1
votes

Try event.cancelBubble = true in event handler.

0
votes

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?

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