How to stop keypress
event in keydown
.
I have a keydown
handler in that I need to stop keypress
event.
Ac
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
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.
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.
Try event.cancelBubble = true
in event handler.
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?
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.