Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable keyboard with HTML input and allow scanners

I have an HTML input

<input type="text" id="txtInput">

and I need to disable all keyboard keys for input, only to allow barcode scanners to get the data of the barcode and fill it with the input.

I tried "readonly" and "disabled" and javaScript keydown, but all those solutions disable everything including barcode scanners too.

Is there's any way for doing this?

like image 660
CairoCoder Avatar asked Aug 15 '16 15:08

CairoCoder


1 Answers

So first you need to understand that barcode scanners pretend to be keyboards. So they will trigger JS keystroke events just like real keyboards. The only way I can think of to separate the 2 is some timing-based heuristic (the idea being that nobody can type an entire 10-digit barcode in less than 0.1 seconds).

So basically, you would have some javascript that would do something along these lines:

  • (onkeydown) append the pressed key to a global string and start a timer with setTimeout (with very low delay, say 10 ms)
  • (onkeydown) append the pressed key as before, but don't start the timer again
  • in your setTimeout function, check if the string of keypresses is at least 3 keys (or longer, depending on the barcodes that you expect). If so, write the string to the input field. Otherwise, drop the string
  • rinse and repeat

It's gonna be ugly, but if you're really desperate, it might work

var delay = (function(){
   var timer = 0;
   return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
   };
})();

$("#txtInput").on("input", function() {
   delay(function(){
      if ($("#txtInput").val().length < 8) {
          $("#txtInput").val("");
      }
   }, 20 );
});
like image 52
aross Avatar answered Sep 20 '22 13:09

aross