The Code Behind Barcodes

4.0 Programming a Barcode Generator

In this section, we will use JavaScript to generate a UPC-A barcode. Then, using the knowledge of the structure and function of UPC-A barcodes, we can apply this knowledge using a simple script. There are numerous ways to approach this particular problem. This solution is only one of them.

4.1 The Webpage

Let us begin by creating a new HTML file named upc.html. In this file, we will have both our form for inputting new UPCs and the canvas to which we will render. We will disable redirects by submitting javascript:void(0); and directing the form to our generateBarcode() function.

<!doctype html>
<html>
<head>
  <title>UPC-A Generator</title>
</head>
<body>
  <center>
    <form target="_self" action="javascript:void(0);" onsubmit="generateBarcode()">
      <div id="error" role="alert" style="background:crimson; color:white; padding:0.5em; border-radius:0.25em;" hidden=""></div>
      <inputgroup>
        <input type="number" pattern="^\d{12}" id="upc" name="upc" value="042100005264">
        <button type="button" name="button" onclick="generateBarcode()">Generate</button>
      </inputgroup>

    </form>
  </center>
  <div style="text-align: center"><canvas id="upcCanvas" width="345" height="200"></canvas></div>

  <script type="text/javascript" src="upc.js"></script>
</body>