2

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?

1
  • 1
    onKeyPress:{if(event.key is [a-z0-9]) counter++}. Of course, you have to fill in some blanks. Commented Nov 9, 2012 at 10:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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);
        }     
    });
});​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.