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
3 Answers
Reset to default 3This 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);
}
});
});