2
votes

I have written a javascript on a button which blocks the keypress or keydown event on that control. It works fine with key like Enter but when I press space bar key it event gets fired.

Is there any solution for the same?

2

2 Answers

6
votes

Make sure you're using the correct ascii character code for the keypress event, and make sure you're checking the correct properties for the browser you're testing in. IE uses event.keyCode, others use event.which. The following code works fine for me in IE, Firefox and Chrome:

document.getElementById("hello").onkeypress = function (evt)
{
    var k = evt ? evt.which : window.event.keyCode;
    if (k == 32)
        return false;
}​

http://jsbin.com/ikowo4

1
votes

d actually if you compare keycode 32 its little different. I could resolve this by .keydown and keycode = 32... – A Bright Worker Jun 7 '10 at 10:04

@A Bright Worker: Did you take a look at the jsbin link I provided? It has an input box with the code I used here working just fine in IE, Firefox and Chrome. It will allow any character to be input except for the space character. Beyond that, I'm not sure I understand what your comment is trying to say. – Andy E Jun 7 '10 at 10:07

@Andy: Actually the type of input is a filter button in a grid and which already has some onclick event, so if I use onkeypress the event still gets fired. but if I use onkeydown the onclick event does not. Thanks for your example.. I have modified a bit, you can check it out. jsbin.com/ikowo4/2 – A Bright Worker Jun 7 '10 at 10:38

@A Bright Worker: ahh, that makes it a bit clearer now. Take a look at jsbin.com/ikowo4/4, with your developer tools (Firebug, IE Dev Tools, Chrome Dev Tools, etc) console open. Each event has return false, so the next event in the chain should not fire. This is true in Chrome and IE, which show only the onkeydown event firing, whereas Firefox shows all three events firing. I'm not sure if this even helps you, but it looks like you will have to find out exactly what the differences in each browser before you get closer to your answer. Sorry I couldn't help further, good luck. – Andy E Jun 7 '10 at 11:11

Thanks Andy, Infact my application supports on IE so I do not have problem currently. – A Bright Worker Jun 10 '10 at 7:01