JavaScript onkeypress event entry instance of of press or hold a keyboard key
- 2020-03-30 04:09:20
- OfStack
JavaScript onkeypress event
The onkeypress event is triggered when a user presses or holds down a keyboard key.
Note: there is a slight difference between the onkeypress event and the (link: #) event. The onkeypress event does not handle the corresponding function key. After you specifically change the following example to an onkeydown event, type! Special characters like @#$can tell the difference.
prompt
Internet Explorer/Chrome USES event.keycode to fetch the pressed characters, while browsers such as Netscape/Firefox/Opera use event.which.
With the onkeypress event, only Numbers are allowed
Here's an example of using the onkeypress event to only allow users to enter Numbers in a form field:
<html>
<head>
<script>
function checkNumber(e)
{
var keynum = window.event ? e.keyCode : e.which;
//alert(keynum);
var tip = document.getElementById("tip");
if( (48<=keynum && keynum<=57) || keynum == 8 ){
tip.innerHTML = "";
return true;
}else {
tip.innerHTML = " Tip: enter only Numbers! ";
return false;
}
}
</script>
</head>
<body>
<div> Please enter a number: <input type="text" onkeypress="return checkNumber(event);" />
<span id="tip"></span>
</div>
</body>
</html>