JavaScript onkeypress event
This section illustrates you the use of onkeypress event in JavaScript.
In the given example, we are going to show you how to restrict the user to enter any number into the input field. For this purpose, we have created a text field. On pressing the key to write the text on the textbox, you will see that it will take only characters, not the numbers. This is possible by using the onkeypress event. It occurs when a keyboard key is pressed or held down.
Here is the code:
| <html> <h2>Textbox showing onkeypress event</h2> <script type="text/javascript"> function valid(e){ var num; var chars; var check; if(window.event){ num = e.keyCode; } else if(e.which){ num = e.which; } chars = String.fromCharCode(num); check = /\d/; return !check.test(chars); } </script> Enter text: <input type="text" onkeypress="return valid(event)"/> </html> |
On pressing the key, only characters get inserted in the text field:
Tutorials
- Clear cookie example
- JavaScript getElementById innerHTML
- JavaScript getElementById Style
- Javascript Examples
- JavaScript add row dynamically to table
- New Page 1
- JavaScript Change link
- JavaScript Checkbox getElementById
- javascript clear textarea
- JavaScript Clock Timer
- JavaScript Cookies
- JavaScript Date Difference
- JavaScript duplicate string
- JavaScript Email Validation
- javascript focus input
- JavaScript get excel file data
- JavaScript getAttribute Href
- JavaScript getAttribute Style
- JavaScript getElementById div
- JavaScript getElementById Iframe
- JavaScript getElementById select
- JavaScript Hide Button
- JavaScript Hide Div
- JavaScript hide image
- JavaScript Hide Table Column
- JavaScript Hide Table Rows
- JavaScript Key Event
- JavaScript link
- JavaScript method location
- JavaScript move div
- JavaScript move file
- JavaScript move image
- JavaScript Navigate Back
- JavaScript navigate to page
- JavaScript Navigate to URL
- JavaScript indexOf substring
- JavaScript onkeypress event
- JavaScript Open file
- JavaScript Open link in new window
- JavaScript Open Modal Window


