Is there any way to count how many times [az][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?
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.
$(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);
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.