views:

860

answers:

6

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.

whn user press "enter" key, keydown i trigger the event and having the handler.

form submit will triggered in keypress, so i need to stop the keypress event in my keydown handler.

+2  A: 

Hi!

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

john
event.preventDefault(); is not working in opera
santose
A: 

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.

adatapost
A: 

event.preventDefault(); is not working in opera need to change anything...?

santose
try: event.returnValue = false;
john
A: 

Try event.cancelBubble = true in event handler.

zzandy
A: 

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?

harwig