Canceling the Key Press

Before reading through this page, you might want to check out these solutions first:

If onKeyPress returns false, the event is cancelled and it's as if nothing is typed. For example, this code never allows you to type anything in the field.

this code produces this
<INPUT onKeyPress="return false">
type something:

Notice that the attribute starts with the word "return" which means that the rest of the statement is returned to the field object, canceling or allowing the event. Of course, it usually doesn't make sense to just never allow any typing, so you'll usually want to test if something is true or false. For example, you can only type in these fields if the Engineering checkbox is checked:

<INPUT TYPE=CHECKBOX NAME="engr"> Engineering<BR>
College: <INPUT NAME="college" onKeyPress="return this.form.engr.checked"><BR>
Focus:   <INPUT NAME="focus"   onKeyPress="return this.form.engr.checked">

Which gives us this form:

Engineering
College:
Focus:
Sometimes you want to allow or cancel the event based on which key was pressed. We show how to check which key was pressed in the next page.




About the Author
Copyright 1997-2002 Idocs Inc. Content in this guide is offered freely to the public under the terms of the Open Content License and the Open Publication License. Contents may be redistributed or republished freely under these terms so long as credit to the original creator and contributors is maintained.