I'm trying to write something similar to a 'placeholder' polyfill. I would like to catch the keyup event on an input field and get the char the user entered, so i have this code:
$elem.on('keyup',function(e){
var $this = $(this),
val = $this.val(),
code = (e.keyCode ? e.keyCode : e.which);
console.log(String.fromCharCode(code));
});
The problem is this always returns an Uppercase version of the pressed char, how can i know if the pressed char was uppercase or lowercase?
I know keypress
gives the pressed char but it does not activate on all keypress events (like backspace).
Return values: It returns whether any key is pressed or not and accordingly change the background color. jQuery code to show the working of keyup() Method: Code #1: Below code is used to check if a keyboard key is released after being pressed.
The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase "A" is reported as 65 by all events.
Similar to the toLowerCase() method, the toUpperCase() method changes the string value to uppercase.
You can't easily get this information from keyup because keyup only knows which keys are being pressed, not which letters are being typed. You could check for the shift key being down and you could also try to track caps lock yourself, but if someone pressed it outside the browser, you'll end up getting the wrong case characters.
You could try the keypress event., though jQuery reports it does not always behave the same cross-browser. From the doc:
Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With