I'm developing an online study/survey where I need to count the number of keystrokes that a participant makes. I am asking them to type lrlrlrlrlrlrl... in a text field to simulate walking. Turns out many of the participants (as evidenced by the time spent on the task) are copying and pasting.
I need something that will count keystrokes so I can identify participants who completed the task as requested. The study is programmed in Coldfusion and I was thinking about some sort of javascript/onkeydown/hidden file field combination, but I am not really a programmer.
Any help would be appreciated. Thanks.
HTML:
<input type="text" class="nopaste"/>
<input type="text" id="countstroke"/>
<span id="count"></span>
Javascript:
var strokeCount = 0;
$(function(){
$(".nopaste").bind("copy paste", function(e){
e.preventDefault();
});
$("#countstroke").keyup(function(){
$("#count").text("Count: " + (++strokeCount));
});
});
If you want to take it a step further, you can enforce that only the L and R keys are registered (http://jsfiddle.net/kBJGM/5/):
$("#restrictivecount").keypress(function(e){
var seq = rstrokeCount % 2;
var allow = true;
switch(e.keyCode){
case 76:
case 108: // L or l
if (seq == 1) allow = false;
break;
case 82:
case 114: // R or r
if (seq == 0) allow = false;
break;
default:
allow = false;
break;
}
if (allow)
$("#rcount").text("Count: " + (++rstrokeCount));
else
e.preventDefault();
});
var keyPressCount = 0;
$(document).on("keydown",function(){
keyPressCount++;
});
check out this fiddle
count=0;
$(document).bind('keydown', function(event){
var keyCode = event.keyCode;
switch(keyCode){
case 39:
alert('Right arrow was pressed');
count++;
break;
case 37:
alert('Left arrow was pressed');
count++;
break;
}
});
You must have jQuery library to make this work.
来源:https://stackoverflow.com/questions/12111262/simple-javascript-keystroke-count