Saturday 1 September 2012

Add Keypress in HTML File with Javascript



In HTML control, If we want to use Keypress event then we use JavaScript code which described as follows


  1. First we Open a Text Editor and type the following codes
<html>
<head>
</head>
<body>
<p>
A function is triggered when the user presses a key in the input field. The function alerts the key pressed.</p>
<input type="text" onkeypress="displayResult()" />
</body>
</html>

2. In the above file we create a html file and add a Textbox for input any value from user. In the above code we declare a Function "displayResult()" for onkeypress. This event is used for add keypress functionality to textbox Now we add javascript function "displayResult()" as like follows :

<script>
function displayResult()
{
var x;
if(window.event) // IE8 and earlier
{
x=event.keyCode;
}
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
keychar=String.fromCharCode(x);
alert("Key " + keychar + " was pressed down");
}
</script>

3. In the above script we used 'event.keyCode' this keyword is used for fetch an assign a keypress value to variable 'x'. In other line we declare a vaiable 'keychar' and then assign the value to it after convert it into character, because 'event.keyCode' keywork only fetch 'ASCII code'. for example if we press 'a' then its ASCII code is 65, which is further convert into string value by using the syntext :
x=event.keyCode;
keychar=String.fromCharCode(x);

4. In the following line of this script we show this keyword on screen in form of a message box by using alert command as like :
alert("Key " + keychar + " was pressed down");

Please download the example given below :
 
Keypress Event



No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Twitter Bird Gadget