Doing real-time calculations in a form using JavaScript

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;">
    <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'
    <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>
    <label for='includecandles' class="inlinelabel">
    Include Candles($5)</label>
    <input type="checkbox" id="includecandles" name='includecandles'
    onclick="calculateTotal()" />

    <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"  />
    <div id="totalPrice"></div>


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
//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();

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

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();

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

Comments on this entry are closed.

  • Hi,

    Can someone give me the code for the earning calculator similar to neobux?


  • Dear Coder, I am Javascript learnerm and its my first time to see this best website i’ve seen up to now, so i would like to change this Combo for Price calculation:

    var arr = new Array();
    arr[0] = new Array(“-select-“);
    arr[1] = new Array(“Shirt”,”T-Shirt”,”Trouser”);
    arr[2] = new Array(“Camel”,” Cow”,”Fish”,”Chicken”,”Goat”);

    function change(combo1){
    var comboValue = combo1.value;
    for (var i=0;i<arr[comboValue].length;i++){
    var option = document.createElement("option");
    option.innerHTML = arr[comboValue][i];


    Best Regards.

  • Great post, great application!
    Thank for share, I love it!

  • Never mind guys, I got it! It was:

    if(includeCandles .checked==true)

  • hello,

    can someone please help me: if I want to add a second checkbox with the same price as “candlesPrice” (5$) how would I write it.

    I wrote:

    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”];
    var includeCandles2 = theForm.elements[“includeCandles2”];
    //If they checked the box set candlePrice to 5
    if(includeCandles .checked==true)
    //finally we return the candlePrice
    return candlePrice;

    This code gives me 5$ only if both are checked. I would like them to each be 5$. And I would need a solution good for multiple checkboxes (I would have around 30 checkboxes with different prices).


  • How do I get totalPrice to be with two decimal places (ie 5.00). I need to pass this field onto the credit card processing company in this format.

  • Hello, thank you very much fot this tutorial. Can some one help me with some function into this form?

    How i can add some othet input text with click to “Add additional text” in this form with JS/AJAX?

  • This is exactly what I need! Just one issue though, all the variables are assigned manually in the .js file — how would I go about customising this so it will auto add from multiple drop down boxes with pre-assigned variables which can change (always a number, which can be used to add together)

    • Sorry should have posted this together. This is the code I have and need to be able to add together:

      foreach ($_SESSION[‘topping’] as $value) {
      echo “Topping$value”;
      $counter = 1;
      while ( $counter <= $_SESSION['cupcake'] ) {
      echo '’.$counter.”;

  • thank u soooooooo much!

  • This is awesome! Thanks! Now I’m trying to insert the totalPrice into a database via php/mysql. How would I set up totalPrice as a value/name so I can process it?

    • this is awesome! i was able to build an online quote for customers in just a few hours and i’m a JS novice. question: how can i get the “submit” button to send me the completed “ordered” via email?

  • Thank you for this!

  • Hi there, thank you very much for your useful tutorial.
    i need to get 4 Decimal places for the result.
    can you anyone tell me how i could do this?
    looking forward for your help.

    • in php simply use the function
      $newvar = number_format($var, 4)

  • Thank you so much, thats really helpful… Thank you.

  • Thank you for this script. It is very close to what I am looking.
    (Feel free NOT to publish this comment but I would appreciate if you can get back to me)

    Question: How can I adapt something like this to display text instead of numerical values. For example; option 1 (radio button 3), option 2 (radio button 1), option 3 (radio button 2), results equals a text value.

    I am trying to find a script that would allow people to select from a set of options using radio buttons and the script will give a result (link) based on their answers.

    I hope this makes sense.

    Thanks for your help.

  • Thanks for the example, it was very useful.
    What if you wanted to pick multiple options (eg. for decoration)?
    A multi-select box would work, where a list of possible decorations would be on the left side, and they would be picked with a > button to move them to the right side.

    Is there a way to populate the list of decorations (on the left side) from an array or CSV file? This would make maintenance (adding/changing items or decorations) much easiier..

    ..and we still have to calculate the price of the picked items.

  • Can anyone provide a working example of the following. Say the customer wants the $5 candles but the COST is $5 each and they want to limit the purchase to 4 candles.

    They would need a blank field where they could enter the number of candles wanted.
    4 candles at $5 = 20

  • It would be great if you add the “Using text box in a calculation” into the demo form.
    Thanks – great easy to understand information.

  • Hello, thank you for so nice post.
    Just small bug:

    function getQuantity()
    //Assume form with id=”theform”
    var theForm = documents.forms[“cakeform

    maybe should be:

    function getQuantity()
    //Assume form with id=”theform”
    var theForm = document.forms[“cakeform

    Thanks again!

    • Thanks for finding this error; corrected now.

  • great post…thanks a lot

  • I have encountered problems when doing this! I have several sets of radio buttons, and I have followed exactly what you said and it didn’t work. It worked if I only had 1 set of radio button…. please help???