JavaScript Coder

Doing real-time calculations in a form using JavaScript

calculate with javascript javascript calculate javascript calculator

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”.


<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.