Dynamic or on-the-fly percentage calculations with JavaScript
July 12th, 2009 | Published in javascript
Here is a simple JavaScript function that does dynamic or on-the-fly percentage calculations.
The savings percentage will change dynamically according to the values placed into the MSRP and sales price inputs. The initial 50% percent value was hardcoded in this case to save time but the value will change accordingly.
Here is the plain HTML:
1 2 3 4 5 | <label for="msrp">MSRP</label><input type="text" id="msrp" name="msrp" size="5" value="200" onkeyup="calculatePercentage(this.value, document.getElementById('newprice').value)">
<br/>
<label for="newprice">Sale Price</label><input type="text" id="newprice" name="newprice" size="5" value="100" onkeyup="calculatePercentage(document.getElementById('msrp').value, this.value)">
<br/>
<div><strong>You have saved</strong> <span id="results" style="color: green; font-size: 1.5em;">50</span> <strong>%</strong></div> |
Lines 1 and 3 is where all the action is. The JavaScript function, calculatePercentage, is executed everytime the onkeyup even listener fires and passes the MSRP and Sale Price arguments. As you probably know already, the onkeyup event occurs everytime a keyboard key is released. That is how we are constantly calculating and updating the percent savings.
Here is the JavaScript code for calculatePercentage:
1 2 3 4 | function calculatePercentage (oldval, newval) { percentsavings = ((oldval - newval) / oldval) * 100; document.getElementById("results").innerHTML = Math.round(percentsavings*100)/100; } |
This is a very simple percentage calculation function that places the results, that have been rounded to 2 decimal places, into the results div. For the sake of brevity, there is no validation for the user input but the function will return NaN (Not a Number) if it is not able to calculate a percentage.
Share with a friend:Customize message