Simple Javascript Billing System (Step-By-Step Guide)

Welcome to a tutorial on how to create a simple Javascript billing system (or bill generator). Yes, I did a quick search, and the top results are pretty much assignments done by students – They are pretty cool, but let this code ninja show you a couple more tricks. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes JS Billing Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

JAVASCRIPT BILLING

All right, let us now get into the details of building a Javascript bill generator from scratch.

 

STEP 1) THE HTML

1-js-bill.html
<!-- (A) ITEMS -->
<div id="items"></div>
 
<!-- (B) BOTTOM NAVIGATION -->
<div id="bottom">
  <!-- (B1) TOTAL AMOUNT + PRINT -->
  <div id="bottomA">
    <div id="totalA">$ <span id="totalB">0</span></div>
    <button id="bPrint" type="button">
      <span class="mi">print</span>
    </button>
  </div>
 
  <!-- (B2) ADD ITEM -->
  <form id="bottomB" onsubmit="return false">
    <input type="number" id="addQty" min="1" value="1" required/>
    <input list="addItems" id="addItem" required/>
    <datalist id="addItems"></datalist>
    <input type="number" id="addPrice" min="0.00" step="0.01" value="0.01" required/>
    <button id="addButton" type="submit">
      <span class="mi">add_box</span>
    </button>
  </form>
</div>

This may seem a little intimidating for some beginners at first, but keep calm and look carefully – The page itself is split into two parts, top and bottom.

  1. The top part is a simple <div id="items"> container to show all the items in the “cart”.
  2. The bottom part is further split into 2 sections.
    • (B1) The total amount, and a “print bill” button.
    • (B2) A form to add an item to the “cart” – Quantity, item name, and price (each). Take note of the empty <datalist> here, we will do some Javascript magic to better handle the autocomplete.

 

 

STEP 2) THE JAVASCRIPT

COMMON ITEMS

2-js-bill.js
// (A) COMMON ITEMS NAME & PRICE
items : {
  "Apple" : 1.1, "Beet" : 2.2, "Cherry" : 3.3,
  "Durian" : 2.3, "Eggplant" : 1.2, "Fig" : 2.1
}

The first part of the Javascript is nothing but a simple bill.items object to keep all the common products. Captain Obvious to the rescue, this is in the format of NAME : PRICE.

 

INITIALIZE

2-js-bill.js
// (B) INITIALIZE BILLING
init : () => {
  // (B1) ADD COMMON ITEMS TO DATA LIST
  let list = document.getElementById("addItems");
  for (let [k,v] of Object.entries(bill.items)) {
    let opt = document.createElement("option");
    opt.innerHTML = k;
    list.appendChild(opt);
  }
 
  // (B2) ALSO POPULATE PRICE IF KNOWN ITEM
  let item = document.getElementById("addItem"),
      price = document.getElementById("addPrice");
  item.onchange = () => { if (bill.items[item.value]) {
    price.value = bill.items[item.value];
  }};
 
  // (B3) INITIALIZE FORM + PRINT
  document.getElementById("bPrint").onclick = bill.print;
  document.getElementById("bottomB").onsubmit = bill.add;
}
window.addEventListener("load", bill.init);

On window load, bill.init() will initialize the app.

  • (B1) Remember the empty <datalist> from earlier? Yes, we loop though bill.items to populate it dynamically.
  • (B2) Now, the sad part about <datalist> is that they can only populate a single <input>. But in this case, we need it to populate both the item and price. Thus, this extra bit of code.
  • (B3) Self-explanatory. “Enable” the print and add item buttons.

 

 

ADD ITEM TO “CART”

2-js-bill.js
// (C) ADD AN ITEM
add : () => {
  // (C1) GET HTML FIELDS
  let hItems = document.getElementById("items"),
      hQty = document.getElementById("addQty"),
      hItem = document.getElementById("addItem"),
      hPrice = document.getElementById("addPrice");

  // (C2) CREATE NEW ITEM ROW
  let row = document.createElement("div");
  row.className = "row";
 
  let col = document.createElement("div");
  col.className = "qty";
  col.innerHTML = hQty.value;
  row.appendChild(col);
 
  col = document.createElement("div");
  col.className = "name";
  col.innerHTML = hItem.value;
  row.appendChild(col);
 
  col = document.createElement("div");
  col.className = "price";
  col.innerHTML = (+hQty.value * parseFloat(hPrice.value)).toFixed(2);
  row.appendChild(col);
 
  col = document.createElement("button");
  col.innerHTML = "<span class='mi'>delete</span>";
  col.onclick = () => { bill.del(row); };
  row.appendChild(col);
  hItems.appendChild(row);
 
  // (B3) CLEAR FORM FIELDS + TOTAL
  hQty.value = 1;
  hItem.value = "";
  hPrice.value = "0.00";
  bill.total();
  return false;
}

Yikes! This is scary… not. Look carefully again. This part is essentially just getting the values from the form, and generating the HTML to put into <div id="items">. Long-winded, but not “complicated”.

 

DELETE ITEM ROW & CALCULATE TOTAL

2-js-bill.js
// (D) DELETE ITEM ROW
del : (row) => {
  row.remove();
  bill.total();
},
 
// (E) CALCULATE TOTAL
total : () => {
  let all = document.querySelectorAll("#items .price"),
      amt = 0;
  if (all.length>0) { for (let p of all) {
    amt += parseFloat(p.innerHTML);
  }}
  document.getElementById("totalB").innerHTML = amt.toFixed(2);
}
  • (D) Should be easy enough – We simply remove the entire selected row.
  • (E) This is a so-called helper function to grab all the price tags and calculate the total amount.

 

 

PRINT BILL

2-js-bill.js
// (F) PRINT
print : () => {
  // (F1) GET ALL ITEMS
  let all = document.querySelectorAll("#items .row");
 
  // (F2) PRINT CURRENT LIST
  if (all.length>0) {
    let pwin = window.open("3-bill-print.html");
    pwin.onload = () => {
      // GET PRINT WINDOW ITEMS LIST
      let pdoc = pwin.document,
      list = pdoc.getElementById("items");
 
      // CLONE ROW ITEMS ONLY (MINUS REMOVE BUTTON)
      for (let i of all) {
        let clone = i.cloneNode(true);
        clone.getElementsByTagName("button")[0].remove();
        list.appendChild(clone);
      }
 
      // ADD TOTAL ROW
      let total = pdoc.createElement("div");
      total.className = "total";
      total.innerHTML = "TOTAL: " + document.getElementById("totalB").innerHTML;
      list.appendChild(total);
 
      // PRINT!
      pwin.print();
    };
  } else { alert("No items to bill!"); }
}

The last Javascript print function. Essentially open another HTML page, and “copy” the items over.

 

STEP 3) PRINT PAGE

3-bill-print.html
<header id="head">
  <h1>MY COMPANY</h1>
</header>
<div id="items"></div>

As simple as can be – Up to you to design. It’s just HTML and CSS.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

WHAT’S NEXT?

For you guys who want to use this in a “live setup”… It is probably not a good idea. This is pretty much only one component of the many in a professional system:

  • How about user login? Let everyone access it?
  • Where do you keep the past bills?
  • There has to be a database or store somewhere to keep all of this information.
  • Also, security matters.

So yep, having some form of server-side script and database is still recommended.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Simple Javascript Billing System (Step-By-Step Guide)”

  1. Wow…I loved it. I agree with the comment from Rodrigo, but for me, as an offline quick job quotation maker. I absolutely love it. Already saved in localhost.

  2. this example is promising and very good to use offline as a shopping list made in the market, to know how much you will pay before reaching the checkout

Leave a Comment

Your email address will not be published.