you should use now:e.key === 'Enter'
Here was proposed to use key value instead of keyCode and if it fails then use keyCode. Though this is not enough, because values in this attributes are not compatible. Thing is new key contains the string for control keys, like: ArrowUp, but keyCode will contain just code which with trivial
String.fromCharCode(event.keyCode)
will result in a non-printable char. Here the solution for printable chars:
element.keydown((event) => {var symbolPressed;//cross browserif (event.key !== undefined) {symbolPressed = event.key; //Here control characters represented as String like: ArrowUpif (symbolPressed.length > 1) return; //filter out control characters} else if (event.keyCode !== undefined) {symbolPressed = String.fromCharCode(event.keyCode); //Here control chars represented as one char string}//Update this regex if you need other charactersif (!symbolPressed.match(/[A-z0-9\s]/)) return;console.log(symbolPressed);});
And in case of you need non-printable control characters, you have to update conditions and regex accordingly.
Using onkeypress and onkeydown to event.which, itis switch [CHARACTER code] or [KEYcode]
function myKey(event){var keycode = event.keyCode; //key code variant 1, not recomendatevar keywhic = event.which; //key code variant 2, nice worked var unicode = event.key; //string name code, nice worked var chacode = event.charCode; //works onkeypress="myKey(event)"var metakey = event.metaKey; //true false, winKey or macComanddocument.getElementById("demo").innerHTML = keycode+" "+keywhic+" "+unicode+" "+chacode+" "+metakey;}
<!DOCTYPE html><html><body onkeydown="myKey(event)"> <!--onkeypress="myKey(event)"--><h1 id="demo">Keyboard Buttons click me and test the keyboard</h1><script>//function myKey(event){//paste code//}</script></body></html>
You can use
parseInt(event.key, radix: 10)