How to listen to keyboard type text in Javascript?

I want to get text on the keyboard, not key code. For example, I press shift + f, I get "F" instead of listening to two key code. Another example, I press F3, I did not enter anything. How can I find out what in js? Thanks.

+6
javascript javascript-events events
source share
4 answers

To do this throughout the document, use the keypress event as follows. No other widespread key event at this time will be:

 document.onkeypress = function(e) { e = e || window.event; var charCode = (typeof e.which == "number") ? e.which : e.keyCode; if (charCode) { alert("Character typed: " + String.fromCharCode(charCode)); } }; 

For all key JavaScript related issues, I recommend Jan Wolter an excellent article: http://unixpapa.com/js/key.html

+19
source share

I am using jQuery to do something like this:

 $('#searchbox input').on('keypress', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if(code == 13) { //Enter keycode //Do something } }); 

EDIT: since you are not snapping to a text field, use:

 $(window).on('keypress', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if(code == 13) { //Enter keycode //Do something } }); 

http://docs.jquery.com/Main_Page

0
source share

You can listen to the onkeypress event. However, instead of just examining the event.keyCode (IE) or event.which (Mozilla) property, which gives you key code, you need to translate the key code with String.fromCharCode() .

A good demo is on Javascript Char Codes (key codes) . Browse the source and find the displayKeyCode(evt) function.

Additional links: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode () .

0
source share

It is too difficult to answer quickly. This is what I use as the final link to handle the keyboard. http://unixpapa.com/js/key.html

0
source share

All Articles