In this tutorial you will learn how to use JavaScript to calculate total price based on quantity selected for different items. You can see a demo
here.
First, we will create our items. For each item that we create in our table, we will add a quantity text box:
<input name="qnt_1" type="text" id="qnt_1" value="0" size="3" data-price="100">
We name each field qnt_ID where ID starts from 1. When you create the items, make sure to use consecutive IDs as their names are used in the JavaScript function to sum all values. In our example, we created 4 items, each with a different price which is set in the data-price attribute for the corresponding quantity text field. Default values are set to 0 so no items are selected.
Then we created a JS function, CalculateItemsValue(), which checks the values for all quantity fields and sums them
function CalculateItemsValue() {
var total = 0;
for (i=1; i<=total_items; i++) {
itemID = document.getElementById("qnt_"+i);
if (typeof itemID === 'undefined' || itemID === null) {
alert("No such item - " + "qnt_"+i);
} else {
total = total + parseInt(itemID.value) * parseInt(itemID.getAttribute("data-price"));
}
}
document.getElementById("ItemsTotal").innerHTML = "$" + total;
}
We also define a variable for the total number of items that we have:
var total_items = 4;
Now what has left to be done is to add an onkeyup event to each of the quantity boxes. So when a key is pressed and released the CalculateItemsValue() JS function is executed, and the total price is calculated based on quantity selected for each of the items.
There is a div container with ID ItemsTotal where total value is printed using document.getElementById("ItemsTotal").innerHTML.
<div id="ItemsTotal">$0</div>
You can check how this works
here and download the demo page
here.
HOW TO ADD A NEW ITEM
If you need to add new item to the table, follow these steps:
1) Add a new row to the table
<tr>
<td>Item E</td>
<td><input name="qnt_5" type="text" id="qnt_5" value="0" size="3" data-price="99" onkeyup="CalculateItemsValue()" /></td>
<td>$99</td>
</tr>
It will be qnt_5 and price will be 99
2) Change JS variable total_items to 5
var total_items = 5;
3) That's all!
If you have any questions or suggestions about this "Price Calculation Based On Quantity" tutorial, please use the comments form below! Thank you!