w3resource

jQuery: Display the keyboard key which was pressed in a textbox

jQuery Events : Exercise-16 with Solution

Display the keyboard key which was pressed in a textbox.

Sample Data :

<body>Input your name:  <input type="text">
<div></div>
</body>

Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Display the  keyboard key which was pressed in a textbox</title>
</head>
<body>
Input your name:  <input type="text">
<div></div>
</body>
</html>

JavaScript Code:

$( "input" ).on( "keydown", function(event) {
  $( "div" ).html( event.type + ": " +  event.which );
});

Live Demo:

See the Pen jquery-events-exercise-16 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Display the event type on clicking all h1 elements.
Next: Attach a function to the focus event. The focus event occurs (display a message regarding the text field) when the <input> field gets focus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/jquery-events-exercise-16.php