Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javascript Javascriptexamples JavaScript onkeypress event

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript onkeypress event

Advertisement
This page discusses - JavaScript onkeypress event

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:

Download Source Code:

        

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: JavaScript onkeypress event  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com