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.
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.
Comments on this entry are closed.
How can you implement it using chechkboxes?
Found solution here http://codepen.io/dustinleer/pen/JozxNg
Hi Everyone, how about if i have more than one group of radio button, i means how the looping java script, maybe someone can help me.
i want to show user what have selected does anyone know how to do that for example if you choose lemon filling and Round cake 6″ – serves 8 people ($20), i want an aler box to tell them what they have chosen
Hi, I seem to have missed the condition of which the totalPrice Div changes it display property from None to Block. I tried to put a different background color on it and now the background shows through before the calculation is even finished.
hello,
I am a beginner in Java script. I want to increase and decrease quantity of my item (by multiplying quantity) using this code.
how can i do this?
Thank you for this tutorial this got me started down the right path but I am trying to do some complex calculating. Is it possible to use a drop down menu of items that has a change of value using radio buttons? For example: Selecting Chocolate Cake in the drop down menu and then radio buttons would have 3 sizes to change the value?
In case you just need to share a calculation you have made and make an app out of it with clear inputs and outputs I would recommend the new service I came across calcopedia.com. Create the calculation in a spread sheet (javascript can also be used) and share the input and output cells you need.
I very much need help with figuring out how to get a checklist to complete as forms are filled out. I want to translate into java something to the effect of “When all fields on page 1 are complete then checkbox 1 is selected” and I cant quite nail down the correct code. Please let me know how I can make this work!
Hi, I really hope you can help me… I used your tutorial to calculate items inside a website that I’m building. However I’m getting NAN as a result. Please your help is much appreciated.
here is the link http://codepen.io/chanty6680/pen/KzJmWM
thanks to this blog…view my blog: http://www.esyncsecurity.com
hi, can you help me with adding up the cake amount and the dimension?
below is the code:
master
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
0
Home
About us
Join us
Contact us
Products
Yogurt Cake
Eggless Cake
Tofu Cake
Alcohol Cake
Valentines’ Day Special
Other item
Customization
Service & FAQ
Order now!
1.Personal Details
Full Name
A value is required.
E-mail
Invalid email address.Invalid email address
.
Phone Number
A value is required.Invalid format.
Salutation
Mr
Mrs
Ms
Referral
2. Address
Street
A value is required.(e.g. Woodlands street 74)
Block and unit no
A value is required.(e.g. Blk 836 #12-646)
Postal code
A value is required.(e.g. 765235)
Billing address is the same as delivery address.
2.A. Billing Address (ignore if billing address is the same as delivery address.)
Street
(e.g. Woodlands street 74)
Block and unit no
(e.g. Blk 836 #12-646)
Postal number
(e.g. 765235)
3. Cake Ordered
Name of cake ordered:
Baymax Yogurt Cake
Snow Forest
Strawberry flavour yogurt cake
Matcha Flavour yogurt
Rainbow
Creamy Mango
Nest
Doraemon
Tofu cheese cake
Strawberry tofu mix
Chocolate tofu garden
Tofu mountain
Mango Tango
Magarita
Chocolate Vodka Martini
I heart U
Be my bride
Swan Lake
Dimension of cake ordered
15×15 inches
20×20 inches
30×30 inches
Code of cake ordered
4. Payment Methods
Type of payment methods
NETS
VISA
Amercian Express
MasterCard
Please select an item.
Card Number
A value is required.Invalid format.
Terms and Conditions
By ticking the checkbox below, you have agree on the following terms and conditions:
1) The expiry date of your card must not exceed 2 months within the date of transaction.
2) Delivery address must be in Singapore.
3) Please ensure that there is sufficient amount in your bank statement to purchase your order. Otherwise, our company have the rights to cancel your order.
4) Once your order have been confirmed, our company will deduct the full amount from your bank. If you would like to cancel your order, please call our company within 3 working days.
5) The cakes we have baked may differ from the ones shown in our website.
I agree to the terms and conditions stated above.
var sprytextfield1 = new Spry.Widget.ValidationTextField(“spryzip”, “none”);
var sprytextfield2 = new Spry.Widget.ValidationTextField(“validateEmail”, “email”, {validateOn:[“blur”]});
var sprytextfield3 = new Spry.Widget.ValidationTextField(“sprytextfield3”);
var sprytextfield4 = new Spry.Widget.ValidationTextField(“sprytextfield4”);
var sprytextfield5 = new Spry.Widget.ValidationTextField(“sprytextfield5”);
var spryselect1 = new Spry.Widget.ValidationSelect(“spryselect1”);
var sprytextfield9 = new Spry.Widget.ValidationTextField(“sprytextfield9”, “real”);
var sprytextfield10 = new Spry.Widget.ValidationTextField(“sprytextfield10”, “phone_number”);
Copyright © 2016 Mama’s Bakery. All rights reserved.
Sales: (65) 9011 1892 Tel: (65) 6324 3468
About Us • FAQs
This website is best viewed using Microsoft Internet Explorer 9 or higher, or latest version of Google Chrome and Mozila Firefox browsers.
var MenuBar1 = new Spry.Widget.MenuBar(“MenuBar1″, {imgDown:”../SpryAssets/SpryMenuBarDownHover.gif”, imgRight:”../SpryAssets/SpryMenuBarRightHover.gif”});
the slash for the products(or cake) represent the different dimension prices. Can you please help me? I need to help it by 26 Jan, it is for my project…. Thanks
Hi, How can I get the prize in my database to display here in system?
Hi,
i cannot send the totalPrice with the form.I can send all data with the phpform except totalPrice.
I want to send as email and insert into mysql.
How can I get the totalPrice value?
THanks
So I am trying to achieve the following:
– Client inputs price value
– Selects service type (one choice does nothing to the output the other one multiplies it by 625)
– Selects a category from a drop down menu
– Selects delivery or pick up option (one choice does nothing to the output the other one adds 1500)
– Final Price displayed.
I have been working around the cakeform in order to provide the results yet I have been unsuccessful. Any tips out there fellows? Thanks!
Brilliant tutorial – Well explained and helped me out heaps. Thank you very much.
you save my life!! really !! =D
if you wanted the price changes according to the range included in the text field ( for example 20 to 30 has a price and another 40 to 50 ) how can I do ?
I’m sorry for the bad english hope you understand me