Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
537 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...