I have a button and the following javascript routine.
$(\"button\").keydown( function(key) {
switch(key.keyCode) {
case 32: //space
return false;
}
First, if you're detecting a printable character such as space, you would be better off with the keypress event. Secondly, the way to prevent the default action is to call preventDefault() on the event in non-IE browsers and set the event's returnValue property to false in IE.
var button = document.getElementById("button");
button.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
};
I'm not a jQuery expert and I assume it takes care of obtaining the event for you:
$("button").keypress(function(evt) {
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
});