How do I distinguish between a scanner input and keyboard input in Javascript? : <p>I have gone through answers and came across two ways which can help in distinguishing between scanner and keyboard inputs. It can be done through:</p>

<ul>
<li><p><b>Time Based:</b> Scanner inputs are faster than manual keyboard inputs.</p></li>
<li><p><b>Prefix Based:</b> Append a prefix to barcodes or scanners (inbuilt in scanner devices) and use it to identify the scanner inputs. </p></li>
</ul>

<p>Here are the links: <a href="https://stackoverflow.com/questions/11290898/detect-when-input-box-filled-by-keyboard-and-when-by-barcode-scanner">link 1</a>, <a href="https://stackoverflow.com/questions/21633537/javascript-how-to-read-a-hand-held-barcode-scanner-best?noredirect=1&amp;lq=1">link 2</a> which I have used for the references.</p>

<p>The problem which I have run into is that whenever the user manually types some keyboard keys while the scanning event is being fired it gets added to scanner input and leads to inconsistent results. </p>

<p>Here is the code which I am using: </p>

<pre><code>var BarcodeScannerEvents = function(){
  this.initialize.apply(this, arguments);
};

BarcodeScannerEvents.prototype = {
  initialize: function() {
    $(document).on({
      keypress: $.proxy(this._keypress, this)
    });
  },
  _timeoutHandler: 0,
  _inputString: '',
  _keypress: function (e){
    if(this._timeoutHandler){
      clearTimeout(this._timeoutHandler);
    }
    this._inputString += String.fromCharCode(e.which);
    //CHECKS FOR VALID CHARACTERS WHILE SCANNING 
    this._timeoutHandler = setTimeout($.proxy(function(){
      if(this._inputString.length &lt;= 10){
        this._inputString = '';
        return;
      }
      $(document).trigger('barcodescanned', this._inputString);
      this._inputString = '';
    }, this), 20);
  }
};

new BarcodeScannerEvents();
</code></pre>

<p>The format for my barcode is: ~xxx-xxx-xxxxxx where x can be any number between 0-9. If a character which is a number is appended to the barcode it leads to wrong inserts in the database.</p>

<p>I have tried comparing the events from keyboard inputs and scanner inputs but to no avail. I have given a thought of appending extra characters before each digit and then invalidate the scanned barcode if consecutive numbers appear. But I don't feel this is best way to approach this problem. Can someone help me out here? </p>
