开发者

Case sensitive character detection in jQuery's onKeyPress

How to "cas开发者_开发知识库e-sensitively" detect characters onkeypress in jQuery?


Use .keypress and look at the event's which attribute, as described on that page. That page has a Demo section near the bottom where you can type in 'a' and see that which is 97, and then type in 'A' and see that which is 65.

(By the way, I assume you mean "case-sensitively" rather than "case-sensibly".)


See this Fiddle Example

// type 'a': 97
// type 'A': 65
$('input').keypress(function(e){
    console.log(e.which)  
}); 


There's no need for jQuery, which does only the simplest of normalization. As noted elsewhere, the keypress is your only option for key events, and getting the character is pretty simple:

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode) {
        alert("Character typed: " + String.fromCharCode(charCode));
    }
};

Be aware that there a few cases here where you'll get a character alerted for non-printable keys in some browsers, which jQuery wouldn't protect you from (its normalization is almost identical to mine). For more information, see the current definitive reference on JavaScript key events: http://unixpapa.com/js/key.html

I've also written at (slightly) more length on a similar question recently: JavaScript KeyCode vs CharCode


You could simply use string.match() (a plain javascript function)

More details on: link text

Maybe if you give more info we could help you.


One thing to note is that this will only work for keypress, so be careful trying to do this with keydown and keyup. This is from the jquery documentation on keypress:

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜