simple javascript keystroke count

浪尽此生 提交于 2019-12-08 03:29:41

问题


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.


回答1:


http://jsfiddle.net/kBJGM/

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



回答2:


var keyPressCount = 0;

$(document).on("keydown",function(){
   keyPressCount++;
});

check out this fiddle




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!