Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyup event always return uppercase letter

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).

like image 630
Tomer Avatar asked Sep 24 '12 15:09

Tomer


People also ask

What does Keyup return?

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.

What is the use of Keydown and Keyup events?

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.

How will you make your Prem all capital letters Javascript?

Similar to the toLowerCase() method, the toUpperCase() method changes the string value to uppercase.


1 Answers

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.

like image 70
Ed Bayiates Avatar answered Sep 22 '22 21:09

Ed Bayiates