jQuery: Listening for automated scanner input from keyboard?

AP257 picture AP257 · Jan 7, 2011 · Viewed 12.4k times · Source

I'm writing a web app for a library system with a barcode scanner attached. The scanner's input presents as keyboard input, and it's always of the form ~~[\d]+.[\d]+~~, for example ~~470.002~~.

I want to set up a jQuery listener for scanner input, and am a jQuery novice. It should listen to all keyboard input, but only perform an action when it hears input from the scanner, and only when the scanner input has finished.

This is as far as I've got (i.e. not very):

//Global functions: call on all pages.
$(document).ready(function() {
    // Listen for scanner input. 
    $(window).keypress(function(e) {
        var key = e.which;
        if (key==126) {.
            alert('tilde');
            // How to listen for the correct input?
            // check_out_book();
        }
    });
});

What's the best way to keep listening input in the format I need? I'd like it to listen for the final two tildes before calling check_out_book().

I'd also like it to 'stop' listening after the first tilde if there is a pause - to distinguish between a human typist and the automated scanner input. Does jQuery have a way to do this?

Any pointers very much appreciated! Thank you.

Answer

lonesomeday picture lonesomeday · Jan 7, 2011

I think you want to do this by storing what you've received so far and checking to see if it's valid. If it is not, discard what you have received and start again:

$(document).ready(function(){
    var input = '',
        r1 = /^~{1,2}$/,
        r2 = /^~{2}\d+$/,
        r3 = /^~{2}\d+\.$/,
        r4 = /^~{2}\d+\.\d+$/,
        r5 = /^~{2}\d+\.\d+~{1}$/
        r6 = /^~{2}\d+\.\d+~{2}$/;

    $(window).keypress(function(e) {
        input += String.fromCharCode(e.which);

        if (r1.test(input) || r2.test(input) || r3.test(input) || r4.test(input) || r5.test(input)) {
            // input is valid so far, continue
        } else if (r6.test(input) {
            // input is valid and complete
            check_out_book();
        } else {
            // input is invalid, start over
            input = '';
        }
    });
});

You could combine all those regexps into two, but I think it's more legible this way.