Get the keycode for jQuery event
Get the keycode
The following code gets the key code from event.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w . j a va2 s . c om-->
$(window).keydown(function(event){
alert(event.keyCode);
});
});
</script>
</head>
<body>
<body>
<p><input type="text" /> <span>focus event fire</span></p>
</body>
</html>
Escape key
To perform an action when the escape key has been released
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from w w w . j ava 2 s .c o m-->
$(document).keyup(function(event){
if (event.keyCode == 27) {
alert('escaped!');
}
});
});
</script>
<style>
div.dbl { background:yellow;color:black; }
</style>
</head>
<body>
<body>
<p><input type="text" /> <span>focus fire</span></p>
<p><input type="password" /> <span>focus fire</span></p>
</body>
</html>
check key code
How to use event.which to check the key code.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- www . j a v a2 s .c o m-->
$("input").keypress(function (e) {
if (e.which > 65 ) {
alert(e.which);
}
});
});
</script>
</head>
<body>
<body>
<input type="text" />
</body>
</html>
Convert key code to char
The following code converts key code to char in
keypress
event handler.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from w w w . j a v a 2s.co m-->
$("input").keypress(function (e) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>")).children(":last").append(document.createTextNode(c));
$("div").text(e.which);
});
});
</script>
</head>
<body>
<body>
<input type="text" />
<p>Add text - </p>
<div></div>
</body>
</html>