Pessimists, we're told, look at a glass containing 50% air and 50% water and see it as half empty. Optimists, in contrast, see it as half full. Engineers, of course, understand the glass is twice as big as it needs to be. --Bob Lewis

How Do I Suppress a Keystroke in a Browser Input Box Using Javascript?


Frequently, you want to suppress the key press event in Javascript so that the character will not show up in a text box. For example, you want to limit the number of characters that can be entered or you want to allow only numbers. In these cases, you want to suppress the adding of the character to the text box.

The solution is simple. Return false from the onKeyPress event.

Example: Supressing Key Press in Javascript

      <INPUT id="txtChar" onkeypress="return false;" 
            type="text" name="txtChar">

If you try to enter text in the following text box you won't be able to. This works for both Internet Explorer and Netscape.

Sample Input Box:

The Confusion Begins

Well, that was easy. But if you're like me, the more you try to do, the more confused you'll get.

The problem is that a key press generates three different events. When you press a key, the KeyDown event fires. This event is immediately followed by the KeyPress event. If you release the key, the KeyUp event will fire.

When you press a key and hold it you will immediately get the KeyDown and KeyPress events. If you hold the key down long enough, it will start to repeat and for each repeat the KeyDown and KeyPress events will fire repeatedly.

But don't make the mistake I did of thinking that you can suppress the adding of a character to a text box in the KeyDown event. You can set the value of the text box and return false (to hopefully cancel the event, don't forget to say a prayer, too). In some browsers this will actually cancel adding the character to the textbox, but in others it will not.

The best way to suppress (across browsers--the ones I've tested) the character from being added to the text box is to return false from the onKeyPress event handler, NOT the onKeyDown or onKeyUp events.