Pages

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

MSRP (in dollars)

Sale Price (in dollars)

You have saved50%

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.

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.

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.
View all posts by Allen Liu