Santhosh
Santhosh

Reputation: 20456

Stop keypress event

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.

Upvotes: 45

Views: 125256

Answers (7)

ankit singh
ankit singh

Reputation: 306

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

Upvotes: 0

ESP32
ESP32

Reputation: 8723

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.

Upvotes: 5

john
john

Reputation: 888

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

Upvotes: 70

treecoder
treecoder

Reputation: 45181

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.

Upvotes: 4

harwig
harwig

Reputation: 201

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?

Upvotes: 0

zzandy
zzandy

Reputation: 2353

Try event.cancelBubble = true in event handler.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94653

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.

Upvotes: 1

Related Questions