VirtualMV/JavaScript/Case Study: Forms/Calculations
Performing calculations on an HTML Page using JavaScript
Right, lets look at how to do some calculations. In the HTML file I have the following fields that will hold totals.
<div> <h4>Totals</h4> <span class="lbl120">DVD</span> <input name="txtTotalDVD" type="text" disabled="disabled" size="20" style="text-align:right"><br> <span class="lbl120">Blu-Ray</span> <input name="txtTotalBluRay" type="text" disabled="disabled" size="20" style="text-align:right"><br> <span class="lbl120">Total </span> <input name="txtTotal" type="text" disabled="disabled" size="20" style="text-align:right"><br> </div>
Some tricky code here
- disabled="disabled" means that the input box is not able to be edited by the user
- style="text-align:right" means that the numbers will be right aligned (which makes more sense for numbers)
- Note I use txt for the input variables as ALL form variables are txt (even if they are entered as numbers).
Then when the function fnCheckData() is run, the following code will be called
document.myForm.txtTotalDVD.value = vntDVD.toFixed(2); document.myForm.txtTotalBluRay.value = vntBluRay.toFixed(2); var vntItems = vntDVD + vntBluRay; document.myForm.txtTotal.value = (vntItems).toFixed(2);
So I am going to create variables vntDVD, vntBluRay and vntItems (vnt stands for variant which means it can be either text or a number so use with care).
- Where
- vntDVD will be the total for DVDs
- vntBluRay will be the total for BluRays and
- vntItems will be the sum of vntDVD and vntBluRay (add them together!!)
- toFixed(2) means show the number to two decimal places
Ok, before you go hog wild and create the table, test that your code actually works. So, for now add some fixed variables into the code. To make it easier to keep the calculation code separate from the overall structure, I am going to bundle the code into a separate function and call this when fnCheckData is called. So first create fnComputeTotals() before fnCheckData
function fnComputeTotals() { var vntDVD = 123.45; var vntBluRay = 678.123; document.myForm.txtTotalDVD.value = vntDVD.toFixed(2); document.myForm.txtTotalBluRay.value = vntBluRay.toFixed(2); var vntItems = vntDVD + vntBluRay; document.myForm.txtTotal.value = (vntItems).toFixed(2); }
Then add fnComputeTotals to fnCheckData():
fnComputeTotals();
Test the code in your Web Browser to see if its all working. Just a hint, if things aren't working try commenting out the code until it works.
At this stage it's probably time to create an Archive Version.
References
virtualMV | Superquick wiki guide | Please give me some feedback |
VirtualMV/JavaScript/Case Study: Forms/Calculations. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 5, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/Case_Study:_Forms/Calculations (zotero)
|