jquery listen for keypress code example

Example 1: jQuery Arrow Keys Binding Examples

<html>
<head>
<title>jQuery Arrow Keys | Bind Arrow Keys using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>

Hit the arrows keys on your keyboard to see the alert!

<script type="text/javascript">

$(document).keydown(function(e){

	//e.which is set by jQuery for those browsers that do not normally support e.keyCode.
	var keyCode = e.keyCode || e.which;

    if (keyCode == 38) 
	{ 
       alert( "Up arrow key hit." );
       return false;
    }

    if (keyCode == 40) 
	{ 
       alert( "Down arrow key hit." );
       return false;
    }

    if (keyCode == 37) 
	{ 
       alert( "Left arrow key hit." );
       return false;
    }

    if (keyCode == 39) 
	{ 
       alert( "Right arrow key hit." );
       return false;
    }

});

</script> 
</body>
</html>

Example 2: jqueryonkey press

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<script>
count = 0;
$(document).ready(function(){
  $("input").keypress(function(){
    $("span").text(count = count+1);
  });
});
</script>
</head>
<body>

<h2>jQuery keypress event example on Beginnersbook.com</h2>
Write anything here: <input type = "text">
<p>The current characters count in the textbox is: <span>0</span></p>
</body>
</html>

Tags:

C Example