Detect scanner input using jquery

前端 未结 3 770
逝去的感伤
逝去的感伤 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.

提交回复
热议问题