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

前端 未结 11 2068
星月不相逢
星月不相逢 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条回答
  •  -上瘾入骨i
    2020-12-01 01:42

    The solution from Vitall only works fine if you already hit at least one key. If you don't the first character will be ignored (if(this._timeoutHandler) returns false and the char will not be appended).

    If you want to begin scanning immediately you can use the following code:

    var BarcodeScanerEvents = function() {
    	this.initialize.apply(this, arguments);
    };
    
    BarcodeScanerEvents.prototype = {
    	initialize : function() {
    		$(document).on({
    			keyup : $.proxy(this._keyup, this)
    		});
    	},
    	_timeoutHandler : 0,
    	_inputString : '',
    	_keyup : function(e) {
    		if (this._timeoutHandler) {
    			clearTimeout(this._timeoutHandler);
    		}
    		this._inputString += String.fromCharCode(e.which);
    
    		this._timeoutHandler = setTimeout($.proxy(function() {
    			if (this._inputString.length <= 3) {
    				this._inputString = '';
    				return;
    			}
    
    			$(document).trigger('onbarcodescaned', this._inputString);
    
    			this._inputString = '';
    
    		}, this), 20);
    	}
    };

提交回复
热议问题