scanner

by ethanpil

HTML

<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@1.*/css/pico.min.css">
<h1>Item List</h1>
<div class="container">

<div class="grid">
  <video autoplay></video>
  <button id="ok" onclick="">Scan</button>
</div>

<div class="grid">
  <input id="itemlookupcode" placeholder="Barcode">
  <button id="ok" onclick="processScan()">OK</button>
</div>

<table id="reporttable">
  <thead>
    <td>Code</td>
    <td>Count</td>
    <td style="width:66%;">Description</td>
  </thead>
  <tbody id="report">
  </tbody>
</table>

</div>

CSS

h1 { text-align: center; }

JavaScript

let timeout = 100;
let scans = {};
let code = "";
let reading = false;
let codebox = document.getElementById("itemlookupcode");

codebox.addEventListener('keypress', e => {
  //usually scanners throw an 'Enter' key at the end of read
   if (e.keyCode === 13) {
   		processScan();          
    }

    //run a timeout at the first read and clear everything
    if(!reading) {
        reading = true;
        setTimeout(() => {
            codebox.value = "";
            reading = false;
        }, timeout); 
    }
});



function processScan() {
	itemlookupcode = codebox.value;
  
	if (scans[itemlookupcode] === undefined) {
  	scans[itemlookupcode] = 1;
	} else {
  	scans[itemlookupcode] += 1;
  }
  tally();

}

function tally() {
   //Clear the current data
  document.getElementById('report').innerHTML = ''; 
  
  //Append the new data
  var tableRef = document.getElementById('reporttable').getElementsByTagName('tbody')[0];
  //Object.entries(scans).forEach(([key, value]) => console.log(key +"=>"+ value));
  
  for (const [key, value] of Object.entries(scans)) {
    var newRow = tableRef.insertRow(tableRef.rows.length);
    newRow.innerHTML = '<td>'+key+'</td><td>'+value+'</td>';
  	//console.log(`${key}: ${value}`);
	}


}