javascriptinputbarcodebarcode-scannerhidden-field

Javascript: Hidden Input Barcode Scanner


Here's my current setup: I have a barcode scanner in keyboard mode. I am trying to scan to a hidden and out of focus input. The barcode I am trying to read is as follows: asterisk [barcode-info] asterisk.

<form method="post">
  <input type="hidden" name="action" value="barcode-scan"/>
  <input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>

When a barcode input is made, Javascript should capture it and update the "barcode-input" hidden input, which will then submit itself to the server.

Someone recommended trying to use a paste event listener, but it simply didn't seem to capture the input at all.

Update: because of wonderful suggestions below, I've been able to get the input working! The form will test to see if two specific inputs follow each other, then it will execute the next function. Otherwise, it will erase any information contained in the log const. Ultimately, yes, I got this working correctly!

document.addEventListener('keyup', function(e){
        const log = document.getElementById('barcode-input');
        log.textContent += ' ' + e.code;
        document.getElementById('barcode-input').value = log.textContent;

        if (log.textContent.startsWith(' ShiftLeft')) {

            if (log.textContent.startsWith(' ShiftLeft Backslash')) {
            document.getElementById('barcode-input').form.submit();
            console.log('e.code, submit barcode info');
            }
        }

        else {
            log.textContent = '';
            document.getElementById('barcode-input').value = '';
        }
    });

Solution

  • Without an input[type="text"] element on the screen, you will need to capture the keyboard input manually. Something along the lines of:

    document.addEventListener('keydown', (ev) => {
      if (ev.ctrlKey || ev.altKey) return;  // Ignore command-like keys
      if (ev.key == 'Enter') {
        // ...submit the content here...
      } else if (ev.key == 'Space') { // I think IE needs this
        document.getElementById('barcode-input').value += ' ';
      } else if (ev.key.length == 1) { // A character not a key like F12 or Backspace
        document.getElementById('barcode-input').value += ev.key;
      }
    });
    

    That should get you most of the way...