Detect when input box filled by keyboard and when by barcode scanner.

前端 未结 11 2080
星月不相逢
星月不相逢 2020-12-01 00:44

How I can programmatically detect when text input filled by typing on keyboard and when it filled automatically by bar-code scanner?

11条回答
  •  佛祖请我去吃肉
    2020-12-01 01:30

    Adapted the super useful Vitall answer above to utilize an IIFE instead of prototyping, in case anyone just seeing this now is into that.

    This also uses the 'keypress' event instead of keyup, which allowed me to reliably use KeyboardEvent.key, since KeyboardEvent.which is deprecated now. I found this to work for barcode scanning as well as magnetic-strip card swipes.

    In my experience, handling card swipes with keyup caused me to do extra work handling 'Shift' keycodes e.g. a Shift code would be followed by the code representing '/', with the intended character being '?'. Using 'keypress' solved this as well.

    (function($) {
        var _timeoutHandler = 0,
            _inputString = '',
            _onKeypress = function(e) {
                if (_timeoutHandler) {
                    clearTimeout(_timeoutHandler);
                }
                _inputString += e.key;
    
                _timeoutHandler = setTimeout(function () {
                    if (_inputString.length <= 3) {
                        _inputString = '';
                        return;
                    }
                    $(e.target).trigger('altdeviceinput', _inputString);
                    _inputString = '';
    
                }, 20);
            };
        $(document).on({
            keypress: _onKeypress
        });
    })($);
    

提交回复
热议问题