How to Find Out What Character Key Is Pressed

How to find out what character key is pressed?

"Clear" JavaScript:

function myKeyPress(e){
var keynum;

if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}

alert(String.fromCharCode(keynum));
}
<input type="text" onkeypress="return myKeyPress(event)" />

How to detect if the pressed key will produce a character inside an input text-box?

This I think will do the job, or if not is very close and will need only minor tweaking. The thing you have to remember is that you can't reliably tell anything at all about any character that may be typed in a keydown or keyup event: that all has to be done in a keypress handler. The definitive resource for key events is http://unixpapa.com/js/key.html

You also need to consider pastes, which this code won't handle. You will need to have separate paste event handler (although this event isn't supported in Firefox < 3.0, Opera, and very old WebKit browsers). You'll need a timer in your paste handler since it's impossible in JavaScript to access the content that's about to be pasted.

function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}

<input type="text" onkeypress="alert(isCharacterKeyPress(event))">

Get Key Value of Key Pressed with javascriiipt

Use string.charCodeAt(0) to get the lower 16 bits of the first character in a primitive string value encoded using UTF-16, which is the encoding method used by JavaScript internally to represent strings in memory.

If the UTF-16 encoded value is less than 128, the key can be represented in ASCII. However, to get ASCII control code values, use the least significant 4 bits of the ASCII letter encoding.

window.addEventListener('keydown',e => {
let ascii, key = e.key;
if(key.length == 1) {
ascii = key.charCodeAt(0);
if(ascii < 128 && e.ctrlKey) {
ascii = ascii & 0x1f;
}
}
if( typeof ascii == "number" && ascii < 128) {
console.log(`ASCII code ${ascii} entered from keyboard`);
}
else {
console.log( key + " is not in the ASCII character set");
}
});
Type an ASCII letter.

Find out the character pressed key

You left out a pretty important part of the quote or it was missing where you found it:

For example, if you press Shift+3, the
getASCIICode() method returns # on a
Japanese keyboard, just as it does on
an English keyboard.

http://livedocs.adobe.com/flex/201/langref/flash/events/KeyboardEvent.html

This is probably more helpful:

The charCode property is the numeric value of that key in the current character set (the default character set is UTF-8, which supports ASCII).

http://livedocs.adobe.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000480.html

Your application determines what characters set is used, meaning that the even if you have to use separate keys of different keyboard locals to produce the same character, it will have the same charCode.

How to decode character pressed from jQuery's keydown()'s event handler

For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.

var c = String.fromCharCode(e.which) // or e.keyCode

Just remember that for keydown() and keyup(), you'll have to keep track of the case using the e.shiftKey state.

How can I detect the pressed key in VB.NET

This tells you what key was pressed:

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress 

MsgBox(e.KeyChar)

End Sub

You should be able to rework it to suit your needs.

Edit:

If you need to detect non-character key presses such as F1 etc. you can't use the keypress event as it is not raised by non-character keys. Then you will have to use the KeyUp or KeyDown event. I prefer the KeyUp event for one simple reason, the KeyDown event fires as long as the key it kept down, so keep that in mind.

Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp

MessageBox.Show(e.KeyValue)

End Sub

This will return the int number of the key that was pressed, but it does not distinguish between upper and lower case.

You should be able to detect these with something like this:

If Control.ModifierKeys = Keys.Shift Or Control.ModifierKeys = Keys.Control Then
MsgBox("SHIFT or CTRL key pressed with " & e.KeyValue & ".")

Else

MessageBox.Show(e.KeyValue)

End If

Example Usage: To see if the enter key for example was pressed:

Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp

IF e.KeyValue = 13 Then

MessageBox.Show("Enter Key Was Pressed")

End If

End Sub

For a list of what value represents what key see:

Dec      Char                       Dec Char      Dec Char     Dec Char
-------------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL

ASCII table was found at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

How do I detect keypresses in Javascript?

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});

function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

  • https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener

With jQuery:

$(document).on("keypress", function (e) {
// use e.which
});

Reference:

  • http://api.jquery.com/on/

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

  • http://www.jscripters.com/jquery-disadvantages-and-advantages/


Related Topics



Leave a reply



Submit