You are here: Home » All Posts » Javascript Form Handling » Doing real-time calculations in a form using JavaScript

Doing real-time calculations in a form using JavaScript

in Javascript Form Handling

In this tutorial, we will learn how to perform calculations using JavaScript. It is quite often required to do calculations online in order forms, request quote forms and the like. This tutorial will show you how to use different form elements like drop-down list, radio button, check box and text box in a calculation.

We will be using a ‘cake order form’ as an example. As the user makes selections in the form, the total price is calculated in real time.

Calculation form sample

See the Demo

Working with Form Elements

Before we can start coding the JavaScript, we need to have a form to work with. See the HTML code for the ‘cake order form’ below:

<form action="" id="cakeform" onsubmit="return false;">
   <fieldset>
    <legend>Make your cake!</legend>
    <label >Size Of the Cake</label>
    <input type="radio"  name="selectedcake" value="Round6"
    onclick="calculateTotal()" />
    Round cake 6" -  serves 8 people ($20)
    <input type="radio"  name="selectedcake" value="Round8"
    onclick="calculateTotal()" />
    Round cake 8" - serves 12 people ($25)
    <input type="radio"  name="selectedcake" value="Round10"
    onclick="calculateTotal()" />
    Round cake 10" - serves 16 people($35)
    <input type="radio"  name="selectedcake" value="Round12"
    onclick="calculateTotal()" />
    Round cake 12" - serves 30 people($75)

    <label >Filling</label>

    <select id="filling" name='filling'
    onchange="calculateTotal()">
    <option value="None">Select Filling</option>
    <option value="Lemon">Lemon($5)</option>
    <option value="Custard">Custard($5)</option>
    <option value="Fudge">Fudge($7)</option>
    <option value="Mocha">Mocha($8)</option>
    <option value="Raspberry">Raspberry($10)</option>
    <option value="Pineapple">Pineapple($5)</option>
    <option value="Dobash">Dobash($9)</option>
    <option value="Mint">Mint($5)</option>
    <option value="Cherry">Cherry($5)</option>
    <option value="Apricot">Apricot($8)</option>
    <option value="Buttercream">Buttercream($7)</option>
    <option value="Chocolate Mousse">Chocolate Mousse($12)</option>
   </select>
    <br/>
    <p>
    <label for='includecandles' class="inlinelabel">
    Include Candles($5)</label>
    <input type="checkbox" id="includecandles" name='includecandles'
    onclick="calculateTotal()" />
   </p>

    <p>
    <label class="inlinelabel" for='includeinscription'>
    Include Inscription($20)</label>
    <input type="checkbox" id="includeinscription"
    name="includeinscription" onclick="calculateTotal()" />

    <input type="text"  id="theinscription"
    name="theinscription" value="Enter Inscription"  />
    </p>
    <div id="totalPrice"></div>

    </fieldset>
</form>

This is just basic HTML code for a form. We call a JavaScript function within the “onclick” and “onchange” events of the form elements. This function is what does the calculations and updates the price. We will discuss this later in the tutorial, but it’s good you know why it’s there. For now, we have our HTML code ready so let’s begin coding the JavaScript.

How to reference a form object in JavaScript

Before we can do any calculations in the form, we must first have a reference to the form in our JavaScript code. To get the form object, we use the id attribute. Our form id is “cakeform”.

//In the html code
<form action="" id="cakeform">
//Set various form elements
</form>
//In the javascript code
var theForm = document.forms["cakeform"];

How to use radio buttons in a calculation

In order to use radio buttons in a calculation, we need to give the radio buttons a name. All the radio buttons that belong to the same group should have the same name. This way, if you had more than one group of radio buttons, the code can distinguish which groups go with each other. We gave the radio buttons in our cake form the name “selectedcake”.

<input type="radio"  name="selectedcake" value="Round6" />
 Round cake 6" -  serves 8 people ($20)
<input type="radio"  name="selectedcake" value="Round8" />
Round cake 8" - serves 12 people ($25)
<input type="radio"  name="selectedcake" value="Round10" />
Round cake 10" - serves 16 people($35)
<input type="radio"  name="selectedcake" value="Round12" />
Round cake 12" - serves 30 people($75)

Each type of cake has a different price. We need to take this price in the calculation. However, we do not want to set the value of the radio button to the price of the cake. (when you get the form submission at the server side, it is less helpful if caketype=20 rather than caketype=’Round6′)
In order to map the ‘cake size’ radio button to its price, we use an associative array.

var cake_prices = new Array();
cake_prices["Round6"]=20;
cake_prices["Round8"]=25;
cake_prices["Round10"]=35;
cake_prices["Round12"]=75;

Since there are more than one radio buttons, we need to know which one the user checked. We do this by looping through them and seeing if the current Radio Button is checked.

// getCakeSizePrice() finds the price based on the size of the cake.
// Here, we need to take user's the selection from radio button selection
function getCakeSizePrice()
{
    var cakeSizePrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the cake the user Chooses name=selectedCake":
    var selectedCake = theForm.elements["selectedcake"];
    //Here since there are 4 radio buttons selectedCake.length = 4
    //We loop through each radio buttons
    for(var i = 0; i < selectedCake.length; i++)
    {
        //if the radio button is checked
        if(selectedCake[i].checked)
        {
            //we set cakeSizePrice to the value of the selected radio button
            //i.e. if the user choose the 8" cake we set it to 25
            //by using the cake_prices array
            //We get the selected Items value
            //For example cake_prices["Round8".value]"
            cakeSizePrice = cake_prices[selectedCake[i].value];
            //If we get a match then we break out of this loop
            //No reason to continue if we get a match
            break;
        }
    }
    //We return the cakeSizePrice
    return cakeSizePrice;
}

How to use drop-down list (‘select’ list) in a calculation

Here is the sample drop-down list from the ‘cake form’ example.

<select id="filling">
    <option value="None">Select Filling</option>
    <option value="Lemon">Lemon($5)</option>
    <option value="Custard">Custard($5)</option>
    <option value="Fudge">Fudge($7)</option>
    <option value="Mocha">Mocha($8)</option>
    <option value="Raspberry">Raspberry($10)</option>
</select>

Here, we need to map the price of the filling from the selected value.

We again use an associative array to map to the price. For example, if the user were to choose Lemon then the price would be 5.

var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=5;
filling_prices["Custard"]=5;
filling_prices["Fudge"]=7;
filling_prices["Mocha"]=8;
filling_prices["Raspberry"]=10;

And, here is the script that finds the filling price from the drop down selection

//This function finds the filling price based on the
//drop down selection
function getFillingPrice()
{
    var cakeFillingPrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the select id="filling"
     var selectedFilling = theForm.elements["filling"];

    //set cakeFilling Price equal to value user chose
    //For example filling_prices["Lemon".value] would be equal to 5
    cakeFillingPrice = filling_prices[selectedFilling.value];

    //finally we return cakeFillingPrice
    return cakeFillingPrice;
}

How to use check box in a calculation

We have a check box to select whether to include candles. Here is the HTML code for the checkbox:

Include candles <input type="checkbox" id="includecandles" />

In order to tell whether a check box was checked, we call on the .checked property. If the .checked property is true then the user has checked the check box. If the user checked the check box we set a variable (candlePrice) to 5 otherwise it remains at 0.

//candlesPrice() finds the candles price based on a check box selection
function candlesPrice()
{
    var candlePrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the checkbox id="includecandles"
    var includeCandles = theForm.elements["includecandles"];

    //If they checked the box set candlePrice to 5
    if(includeCandles.checked==true)
    {
        candlePrice=5;
    }
    //finally we return the candlePrice
    return candlePrice;
}

Using text box in a calculation

Suppose we have a textbox for ‘quantity’ . The HTML code follows:

Quantity<input type="text"  name="quantity" id="quantity" />

Since the user enters numeric value directly to the text box, we don’t have keep an associative array to map to a number. We can use the parseInt() function.

Here is the JavaScript function

function getQuantity()
{
    //Assume form with id="theform"
    var theForm = document.forms["cakeform"];
    //Get a reference to the TextBox
    var quantity = theForm.elements["quantity"];
    var howmany =0;
    //If the textbox is not blank
    if(quantity.value!="")
    {
        howmany = parseInt(quantity.value);
    }
return howmany;
}

Getting the totals

Now that we know how to work with the form’s elements we can calculate the prices

We call a function called getTotal() when the forms Radio Buttons,Select,and Checkboxes are chosen. We handled the “onclick” and “onchange” events to call the this function. The onclick is triggered when a user clicks on a Radio Button or Checkbox. The onchange is triggered when the user makes a selection with the Drop-down.

We have four functions in our JavaScript code that all return a number. The getTotal() function calls all four of these functions and adds them to get the total. We then display the total.

function getTotal()
{
    //Here we get the total price by calling our function
    //Each function returns a number so by calling them we add the values they return together
    var cakePrice = getCakeSizePrice() + getFillingPrice() +
                          candlesPrice() + insciptionPrice();

    //display the result
    document.getElementById('totalPrice').innerHTML =
                                      "Total Price For Cake $"+cakePrice;

}

We update the innerHTML of the ‘totalprice’ every time the totals are calculated.

See the demo and download the source. With some changes, you can adapt the downloaded code to any calculation you need in your forms.

Be Sociable, Share!

{ 43 comments… read them below or add one }

barry January 29, 2014 at 10:47 pm

This is perfect – a well explained and commented tutorial. I have used this throughout my site – I just wanted to say Thanks!

Reply

Logan April 30, 2013 at 5:30 pm

Hi,
Instead of displaying the calculated price on the same page, how could you get the price to show up on the next page after submit? what would the code look like?

Reply

Smith January 2, 2014 at 12:53 pm

You can solve this by using a form tag. Below is an exemple:

Your form content should be here

will solve your problem. Instead of ‘index.php’ use your file name.

Reply

greg March 25, 2013 at 4:52 pm

Thanks!!

Reply

Mariano March 14, 2013 at 1:47 pm

I just wanna thank you so much for posting this tutorial. It’s short and wonderfully explained and just what I was needing. I also happen to admire people who share their knowledge in the internet because I learn so much through them. That’s all.

Reply

K K March 12, 2013 at 8:04 pm

Hi, what will you charge to create this kind of form?

Reply

Leslie Heltzen March 8, 2013 at 1:58 pm

Hi, Can you help me. I would like the totalPrice to be passed to the php so I receive the total price in an email. The totalPrice here is hidden in a and I don’t know how to pass it to the php. This is a great tutorial and it has enabled me to make a detailed form. http://www.dallasdressage.org/DDCOnlineEntryForm.html. Your help would really be appreciated.

Reply

Smith January 2, 2014 at 12:51 pm

You can solve this by using a form tag. Below is an exemple:

Your form content should be here

will solve your problem. Instead of ‘index.php’ use your file name.

Reply

Sorin Anghel February 28, 2013 at 11:21 am

Thanks a lot! This helped me very much. Even so I have one doubt. How can I add the quantity to the final price? I tried to multiply the quantity through an array but it doesn’t work. If you can please explain it I will be very grateful. Best!

Reply

leslie@hawaiifunplanner.com February 20, 2013 at 3:53 pm

Hi, Are you able to help me, I have changed your form and my totalprice doesn’t calculate until the last object is selected. The first or second selections show up as $NaN. I have worked it and can’t seem to find my error. Thank you, Les

here is my javascript:
var test1_prices= new Array();
test1_prices["None"]=0;
test1_prices["Intro A"]=22;
test1_prices["Intro B"]=22;
test1_prices["Intro C"]=22;
test1_prices["T/one"]=22;
test1_prices["T/two"]=22;
test1_prices["T/three"]=22;
test1_prices["RT"]=22;
test1_prices["Frst/one"]=22;
test1_prices["Frst/two"]=22;
test1_prices["Frst/three"]=22;
test1_prices["RTF"]=22;
test1_prices["Scnd/one"]=22;
test1_prices["Scnd/two"]=22;
test1_prices["Scnd/three"]=22;
test1_prices["RTTwo"]=22;
test1_prices["Third/one"]=22;
test1_prices["Third/two"]=22;
test1_prices["Third/three"]=22;
test1_prices["Forth/one"]=22;
test1_prices["Forth/two"]=22;
test1_prices["Forth/three"]=22;
test1_prices["Western/Basic1"]=22;
test1_prices["Western/Basic2"]=22;
test1_prices["Western/Prim1"]=22;
test1_prices["Western/Prim2"]=22;
test1_prices["Western/Prim3"]=22;
test1_prices["Western/Prim4"]=22;
test1_prices["Other 15"]=22;

var test2_prices = new Array();
test2_prices["None"]=0;
test2_prices["Intro A"]=22;
test2_prices["Intro B"]=22;
test2_prices["Intro C"]=22;
test2_prices["T/one"]=22;
test2_prices["T/two"]=22;
test2_prices["T/three"]=22;
test2_prices["RT"]=22;
test2_prices["Frst/one"]=22;
test2_prices["Frst/two"]=22;
test2_prices["Frst/three"]=22;
test2_prices["RTF"]=22;
test2_prices["Scnd/one"]=22;
test2_prices["Scnd/two"]=22;
test2_prices["Scnd/three"]=22;
test2_prices["RTTwo"]=22;
test2_prices["Third/one"]=22;
test2_prices["Third/two"]=22;
test2_prices["Third/three"]=22;
test2_prices["Forth/one"]=22;
test2_prices["Forth/two"]=22;
test2_prices["Forth/three"]=22;
test2_prices["Western/Basic1"]=22;
test2_prices["Western/Basic2"]=22;
test2_prices["Western/Prim1"]=22;
test2_prices["Western/Prim2"]=22;
test2_prices["Western/Prim3"]=22;
test2_prices["Western/Prim4"]=22;
test2_prices["Other 15"]=22;

var test3_prices = new Array();
test3_prices["None"]=0;
test3_prices["Intro A"]=22;
test3_prices["Intro B"]=22;
test3_prices["Intro C"]=22;
test3_prices["T/one"]=22;
test3_prices["T/two"]=22;
test3_prices["T/three"]=22;
test3_prices["RT"]=22;
test3_prices["Frst/one"]=22;
test3_prices["Frst/two"]=22;
test3_prices["Frst/three"]=22;
test3_prices["RTF"]=22;
test3_prices["Scnd/one"]=22;
test3_prices["Scnd/two"]=22;
test3_prices["Scnd/three"]=22;
test3_prices["RTTwo"]=22;
test3_prices["Third/one"]=22;
test3_prices["Third/two"]=22;
test3_prices["Third/three"]=22;
test3_prices["Forth/one"]=22;
test3_prices["Forth/two"]=22;
test3_prices["Forth/three"]=22;
test3_prices["Western/Basic1"]=22;
test3_prices["Western/Basic2"]=22;
test3_prices["Western/Prim1"]=22;
test3_prices["Western/Prim2"]=22;
test3_prices["Western/Prim3"]=22;
test3_prices["Western/Prim4"]=22;
test3_prices["Other 15"]=22;

//This function finds the filling price based on the
//drop down selection

function gettest1Price()
{
var test1Price=0;
//Get a reference to the form id=”cakeform”
var theForm = document.forms["SchoolingForm"];
//Get a reference to the select id=”filling”
var selectedtest1 = theForm.elements["test1"];

//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
test1Price = test1_prices[selectedtest1.value];

//finally we return cakeFillingPrice
return test1Price;
}

function gettest2Price()
{
var test2Price=0;
//Get a reference to the form id=”cakeform”
var theForm = document.forms["SchoolingForm"];
//Get a reference to the select id=”filling”
var selectedtest2 = theForm.elements["test2"];

//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
test2Price = test2_prices[selectedtest2.value];

//finally we return cakeFillingPrice
return test2Price;
}

function gettest3Price()
{
var test3Price=0;
//Get a reference to the form id=”cakeform”
var theForm = document.forms["SchoolingForm"];
//Get a reference to the select id=”filling”
var selectedtest3 = theForm.elements["test3"];

//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
test3Price = test3_prices[selectedtest3.value];

//finally we return cakeFillingPrice
return test3Price;
}

function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var SchoolingForm = gettest1Price()+ gettest2Price() + gettest3Price();

//display the result
var divobj = document.getElementById(‘totalPrice’);
divobj.style.display=’block’;
divobj.innerHTML = “Total Cost for Schooling Show $”+SchoolingForm;

}

function hideTotal()
{
var divobj = document.getElementById(‘totalPrice’);
divobj.style.display=’none’;
}

my html

Select Your Test

Test1

None
Intro A $22
Intro B $22
Intro C $22
Training 1 $22
Training 2 $22
Training 3 $22
Rider Test Training $22
First 1 $22
First 2 $22
First 3 $22
Rider Test First Level $22
Second 1 $22
Second 2 $22
Second 3 $22
Rider Test Second Level $22
Third 1 $22
Third 2 $22
Third 3 $22
Forth 1 $22
Forth 2 $22
Forth 3 $22
Western Basic 1 $22
Western Basic 2 $22
Western Primary 1 $22
Western Primary 2 $22
Western Primary 3 $22
Western Primary 4 $22
Other $22

Test2

None
Intro A $22
Intro B $22
Intro C $22
Training 1 $22
Training 2 $22
Training 3 $22
Rider Test Training $22
First 1 $22
First 2 $22
First 3 $22
Rider Test First Level $22
Second 1 $22
Second 2 $22
Second 3 $22
Rider Test Second Level $22
Third 1 $22
Third 2 $22
Third 3 $22
Forth 1 $22
Forth 2 $22
Forth 3 $22
Western Basic 1 $22
Western Basic 2 $22
Western Primary 1 $22
Western Primary 2 $22
Western Primary 3 $22
Western Primary 4 $22
Other $22

Test3

 
Intro A $22
Intro B $22
Intro C $22
Training 1 $22
Training 2 $22
Training 3 $22
Rider Test Training $22
First 1 $22
First 2 $22
First 3 $22
Rider Test First Level $22
Second 1 $22
Second 2 $22
Second 3 $22
Rider Test Second Level $22
Third 1 $22
Third 2 $22
Third 3 $22
Forth 1 $22
Forth 2 $22
Forth 3 $22
Western Basic 1 $22
Western Basic 2 $22
Western Primary 1 $22
Western Primary 2 $22
Western Primary 3 $22
Western Primary 4 $22
Other $22

Contact Details
Name

Address

Phone Number

Reply

Vladimir Polischuk January 25, 2013 at 2:24 am

Here is another JavaScript calculator: http://voynex.com/products/calculator
Written in good OOP style, using 3 tire programming model do tire data, logic and interface.
Can evaluate math and JavaScript expressions of any complexity. Works in all mainstream web browsers.

Reply

Ha Rz January 10, 2013 at 11:28 pm
Larry May 7, 2012 at 1:58 am

How can we force the user to select one of the cakes. At the moment the user can skip to the inscription or candles and submit without a cake selected. Can one cake be selected by default from the beginning?

Reply

Ali Abdul November 11, 2013 at 5:24 pm

I think I can help you? :) alig8900@gmail.com

Reply

Mahmoud April 18, 2012 at 9:04 pm

Dude THANK YOU SO MUCH !

Reply

claudio April 4, 2012 at 10:24 am

This was extremely useful, thank you. I’m just getting mad trying to pass the total price of the “cakeform” to paypal for purchase: I’ve seen a lot of forum and script but I’m not an expert and my attempt failed.
Do you have any suggestion on how I can do it? I would be grateful.
Best,
Claudio

Reply

Robert Marlin April 2, 2012 at 6:38 pm

I was able to adapt this script to make calculations on a form ok, however this form does not submit the form details to an email? So, how is it possible to send the details to the required person? Or am I missing something.

Reply

Martin April 1, 2012 at 12:57 am

Hi,

can you help me made a simple form using checkboxes only?

I want to make a form, when users can choose flowers.
For example:
red roses costs $3 each,
yellow roses costs $4 each,
and blue roses costs $5 each

so the form will look like this:
1) Red Roses ($3 each) and 8 checkboxes (if user will check all checkboxes, the price at the bottom of the form will be $24)
2)Yellow Roses ($4 each) and 8 checkboxes (if user will check all checkboxes, the price at the bottom of the form will be $32 + $24)
3) Blue Roses ($5 each) and 8 checkboxes (if user will check all checkboxes, the price at the bottom of the form will be $40 + $32 + $24)

Your help will be much appreciated!

Reply

Bridget March 20, 2012 at 5:24 pm

Very useful tutorial! One question: what if the price of the icing varied depending on the size of the cake? How would you code for that?

I am trying to develop something with variable rates depending on a previous answer..

Reply

Leave a Comment

Previous post:

Next post: