Calculating Sales Volume in JavaScript

In this tutorial I will show you a way to calculate the total value of the products you sold over a period of time,in a few simple and clear steps. I will be using CSS to nicely style the table. jQuery and vanilla JavaScript will be used for the mathematics in this tutorial. Of course, I will be using dummy data. Let us begin.

Step #1: The table structure

Make a table with 5 columns and as many rows as you need. I have 7 products, so my table will have 9 rows. Look at the image below: the data surrounded with a green square is the result of calculations. The rest is inputted data.


Step #2: The table markup

Step #3: Style the table

Step #4: The math

Here comes the best part: the math. Or don’t you like math. If you do, you are already enjoying this tutorial. If you don’t like math, you will after finishing this tutorial. I promise! 🙂

Create a function named totalSales, the call it:

Step #5: actual code

We eill replace the “// Code here” comment with the actual code that will make the calculations. First, select all rows in the table’s body, these being the rows that contain data needed for the calculations:

Step #6: How many rows contain data?

We need the number of rows that contain data to later loop over them:

Step #7: Get the data that will be used to calculate the total sales volume

For every row we need: the quantity sold from each product, the initial price of each product, the discount of each product. With these values we shall calculate the sales volume for each product:

Step #8: create an empty array called sales , then push product sales into it

Just above the for loop:

Inside the for loop, just above its closing bracket:

Step #9: Calculate the total sales volume

We shall sum the values of the sales array an put the result into the table cell with the id of “tot”.

The entire JavaScript code looks like this:

And we are done. See my result HERE.