Dynamic or on-the-fly percentage calculations with JavaScript


Here is a simple JavaScript function that does dynamic or on-the-fly percentage calculations.

Demo




You have saved 50 %


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. <label for="msrp">MSRP</label><input type="text" id="msrp" name="msrp" size="5" value="200" onkeyup="calculatePercentage(this.value, document.getElementById('newprice').value)">
    
  2. <br/>
    
  3. <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)">
    
  4. <br/>
    
  5. <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. function calculatePercentage (oldval, newval) {
  2.     percentsavings = ((oldval - newval) / oldval) * 100;
  3.     document.getElementById("results").innerHTML = Math.round(percentsavings*100)/100;
  4. }

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.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

Leave a Reply

Your email address will not be published. Required fields are marked *