Detect scanner input using jquery

前端 未结 3 724
逝去的感伤
逝去的感伤 2021-02-06 16:39

Suppose I have two textboxes:




        
相关标签:
3条回答
  • 2021-02-06 17:08

    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.

    0 讨论(0)
  • 2021-02-06 17:15

    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.

    0 讨论(0)
  • 2021-02-06 17:15

    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?

    0 讨论(0)
提交回复
热议问题