Last updated on February 15th, 2022 at 06:36 am

Disable certain character keypress using Javascript

Using the OnKeypress event, you can trap and prevent certain characters (represented by ASCII decimal codes) from being entered in a form field. Just look up the ASCII code for any other characters you wish to block and add it to the script. Unfortunately, Netscape does not support this same functionality.

Prevent all special characters (like !@#$%^&* etc) in textarea

<textarea rows=2 cols=20 name=comments onKeypress="if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) event.returnValue = false;"></textarea>

Using this event, input field will not accept double or single quotes

<input type=text name=txtEmail onKeypress="if (event.keyCode==34 || event.keyCode==39) event.returnValue = false;"/>

This input field only accept numbers

<input type=text name=txtPostalCode onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">


Leave a Reply

Your email address will not be published. Required fields are marked *