LOTUSMS
LOTUSMS

Reputation: 10270

Reading a barcode with javascript

I have a barcode gun scanner reading, barcodes, of course, into input fields. At the moment, I am able to read the barcode but it is returning every digit separately. I need it as a whole string. I have been breaking my skull about this.

For example, I read a bottle of water's barcode, the input field catches the number correctly (i.e. 688267022760). When I console log it, I get independent instances for each digit.

enter image description here

My template (VueJS) triggers the scanner event on input. Which I am not entirely sure if that is the correct event. I tried keydown and keyup as well. Not exactly sure which is the recommended event listener for a scan gun. Anyway this is what I have in my template:

<input id="packageInput" type="text" @input="onBarcodeScanned" />

And in my script:

onBarcodeScanned(barcode) {
  let numbers = barcode.data; //data is the object property I need
  console.log(numbers); //this shows me values I need
  let newarr = []; //creating an emprty array where I assume I need to push data to

  // looping through the data and pushing it to the new array, which does not do what I want but it was my logic
  for (var i = 0; i < numbers; i++) {
    newarr.push(numbers);
  }
},

The desired effect would be to get those independent values in an array and then joined as a string.

P.S.

Reading the barcode property returns a series of objects with lots of handlers for several functions. The property of interest is data. See below an example of the barcode objects enter image description here

How can I do this? I'm stumped

P.P.S I understand the scanner itself comes with a series of instructions to program it. Some of which I don't understand too well. Perhaps there is a type of barcode that returns as a string instead of each digit as an object? The scanner I am using is a Wasp CCDScanner WCS3900

Upvotes: 0

Views: 3113

Answers (1)

IceMetalPunk
IceMetalPunk

Reputation: 5556

onInput runs every time the value changes. Most barcode scanners will simulate keypresses to enter the values they scan, so as far as your app is aware, each digit is a keypress that's changing the value and so it reports each as an input event. An input event's data property is just the part of the input that's changed -- so you're getting one at a time.

You need a way to determine when the input is finished, not whenever it happens. I believe most barcode scanners will simulate pressing ENTER or TAB after a full scan is complete, so that might be what you want to detect, not with an input event, but with a keypress or keyup event.

Upvotes: 1

Related Questions