Detect scanner input using jquery

China☆狼群 提交于 2019-12-03 03:52:58

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.

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.

ED-209

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?

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