-->

Detect scanner input using jquery

2019-03-16 18:32发布

问题:

Suppose I have two textboxes:

<input type="text"id="resourceName" placeholder="Resource name"/>
<input type="text" id="barCode"  placeholder="barCode(EAN-13)"/>

To populate this textboxes I use barcode scanner and keyboard. What I want is a little bit difficult and I don't know how to do this . I can't differentiate when user is populating text boxes with keyboard and when with barcode. I need this becouse i want to implement something like : when user is usign barcode scanner and if we don't have focused textbox ,I want to focus barcode textbox and insert this value in this textbox , and when focused is resourceName textbox , first I want to focus barCode textbox and then to insert this value to this textbox. I don't want to let user insert barcode in resourceName textbox using barcode scanner . The problem is that i can't differentiate events , how user is populating textboxex ?, using barcode scanner or using keyboard. Any help will be appreciated.Thanks a lot

回答1:

Take a look at github jQuery-Scanner-Detection

NPM Package jQuery-Scanner-Detection

jQuery Scanner Detection is a small plugin to detect when user use a scanner (barcode, QR Code...) instead of a keyboard, and call specific callbacks.



回答2:

Going off the idea I suggested in the comments, I came up with this...

var _keybuffer = "";

$(document).on("keyup", function(e) {
    var code = e.keyCode || e.which;
    _keybuffer += String.fromCharCode(code).trim();
    // trim to last 13 characters
    _keybuffer = _keybuffer.substr(-13);

    if (_keybuffer.length == 13) {
        if (!isNaN(parseInt(_keybuffer))) {
            barcodeEntered(_keybuffer);
            _keybuffer = "";
        }
    }
});

function barcodeEntered(value) {
    alert("You entered a barcode : " + value);
}

It keeps a buffer of the last 13 keys pressed and if it's just numbers then it assumes it's a barcode and triggers the barcodeEntered function. This is obviously a hack and assumes that there is no reason anyone would ever type a 13 figure number elsewhere on the page (but you could make it ignore key presses if certain fields had focus etc..)

It captures all key presses on the page, regardless of focus so it should capture you scanning a barcode even when nothing has focus.

Edit: I've added .trim() to the keyboard buffering so that spaces are ignored, as per suggestion from @DenisBorisov.



回答3:

Take a look at jQuery's keypress event

Bind this to your input box and it'll alert you when a user is using their keyboard for barcode input

Also, have you seen this question?