最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jQueryJavascript count how many times a key is pressed - Stack Overflow

programmeradmin0浏览0评论

Is there any way to count how many times [a-z][0-9] keys are pressed from user?

I would like to count how many time he press the keys on an input text.

Any suggestions?

Is there any way to count how many times [a-z][0-9] keys are pressed from user?

I would like to count how many time he press the keys on an input text.

Any suggestions?

Share Improve this question edited Nov 12, 2012 at 7:23 Denys Séguret 383k90 gold badges810 silver badges775 bronze badges asked Nov 9, 2012 at 10:25 Filippo orettiFilippo oretti 49.9k96 gold badges229 silver badges351 bronze badges 1
  • 1 onKeyPress:{if(event.key is [a-z0-9]) counter++}. Of course, you have to fill in some blanks. – John Dvorak Commented Nov 9, 2012 at 10:27
Add a ment  | 

3 Answers 3

Reset to default 3

This code would maintain a map giving for each key the number of key press :

var map = {};
$('input')​​​​.keyup(function(e){
    var key = e.keyCode;
    if (key>=48 && key<=90) map[key] = (map[key]||0)+1;
});​

Demonstration (open the console)

You can find here the relation between the key codes and the chars.

If you want to have a map more readable (with characters as keys instead of key codes), do this :

var map = {};
$('input').keyup(function(e){
    if (e.keyCode>=48 && e.keyCode<=90) {
      var key = String.fromCharCode(e.keyCode);
      map[key] = (map[key]||0)+1;
    }
});​

Demonstration (open the console)

But it would probably be easier to just analyze the string (obtained using val) at end of entry.

This code works, replace #yourinputid with your input's id and the keycode == '13' with the key you want to count, 13 is actually Enter. Just look at nbr's value and you'll know how many time the key was pressed.

var nbr = 0;
    $('#yourinputid').keypress(
       function(event)
       {     
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13'){
            nbr++;  
       }
    });

Good luck.

You can add multiple keycode if you change the condition with OR statements.

DEMO

$(document).ready(function() {
    var count = 0;
    $('#txt').keypress(function(event){
        var key_code = event.keyCode ? event.keyCode : event.which;
        if((key_code  >=97 && key_code  <=122) || (key_code  >=48 && key_code <=57)){
           $('#cnt').html(++count);
        }     
    });
});​
发布评论

评论列表(0)

  1. 暂无评论