Javascript Form How to - Capture key event in a text input field








Question

We would like to know how to capture key event in a text input field.

Answer


 <!--from  w w  w  . ja  v  a  2s . co m-->
<html>
<head>
<script language="JavaScript" type = "text/javascript">
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event){
    if (document.all) //Checks for IE 4.0 or later
    {
      document.form1.text2.value = String.fromCharCode(event.keyCode);
    }
    else if (document.getElementById) //checks for Netscape 6 or later
    {
      document.form1.text2.value = String.fromCharCode(key_event.which);
    }
    else if (document.layers) //Checks for Netscape 4
    {
      document.form1.text2.value = String.fromCharCode(key_event.which);
    }
}
</script>
</head>
<body>
<form name="form1">
    <b>Type value in field:&nbsp; See what you typed:</b><br>
    <input type = "text" name = "text1" onKeyPress="DisplayMsg(event)" size="20">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type = "text" name = "text2" onKeyPress="DisplayMsg(event)" size="20">
</form>
</body>
</html>

The code above is rendered as follows: