BARCODE READER

Detect barcode using handheld scanner. https://stackoverflow.com/questions/11290898/detect-when-input-box-filled-by-keyboard-and-when-by-barcode-scanner/15354814#15354814

by Carl Angelo Nievarez

HTML

<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
  <div class="form-group">
    <label for="">Tracking Number</label>
    <div class="input-group">
      <span class="input-group-addon"><span class="fa fa-qrcode"></span></span>
      <input type="text" class="form-control" id="fg_stock_code" name="fg_stock_code" placeholder="Tracking Number">
    </div>
    <!--This could get via scanning the barcode or qrcode-->
  </div>
</div>

CSS

/* Button Primary */
 
 .btn-primary {
   color: #0275d8;
   background-image: none;
   background-color: transparent;
   border-color: #0275d8;
 }
 
 .btn-primary:hover {
   background-color: #0275d8;
   color: white;
   border-color: #0275d8;
 }

JavaScript

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);
  }
};