Search code examples
javascriptjquerybarcode-scanner

keypress event for handling scanner input returns only first character


I am using Datalogic Heron scanner for bar-code input and using this code for getting the barcode value -

<input type="text" id="scannerBarcode" />

and

<script>
    document.addEventListener("keypress", function(e) {
        alert(e.key);
        $("#scannerBarcode").val(e.key);
        e.preventDefault();
        });      
</script>

I am getting two issues -

  1. Using e.key only returning the first character. I don't know how to capture the complete bar-code value. When I have the focus on a simple txt file then barcode shows whole value.
  2. The alert flashes and doesn't wait for me to click OK.

This is my first day with any scanner, so please bear if this is a silly question.

Can anyone please guide how to fix above.

Thank you!


Solution

  • The problem is barcode scanners are standard keyboard inputs, but without sending that value to an input field, you won't get the entire string as you noticed. You can try my answer in regards to the zebra (the same issue) https://stackoverflow.com/a/54769272/3684265

    Another option in keeping with your existing code, is DON'T alert instead APPEND to the barcode value on each keypress.

    var barcode = document.querySelector("#scannerBarcode");
    document.addEventListener("keypress",function(e){
       if(e.keyCode != 13){
           barcode.value += e.key;
       }
       e.preventDefault();
    });
    <input type="text" id="scannerBarcode">