Tuesday, 7 March 2017
Price Calculation Based On Quantity
Price Calculation Based On Quantity
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:
1
| <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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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:
1
| 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.
1
| <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
1
2
3
4
5
| <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> |
2) Change JS variable total_items to 5
1
| var total_items = 5; |
3) That's all!
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment