1. Home
  2. Computing & Technology
  3. JavaScript

Calculator Tutorial

5. Calculate Function

clr gif

The fifth step now that we have our basic form as well as the formula is to attach that formula to the form. To do this we must first convert the formula into a function that the form can call and change the code in the function to retrieve the initial values from the form and return the results to the form.

For my Easter Calculator we end up with the following:

var easterM = new Array('March','April');
function easter() {
var year = calc.year.value;


var a = year % 19;
var b = Math.floor(year/100);
var c = year % 100;
var d = Math.floor(b/4);
var e = b % 4;
var f = Math.floor((b+8) / 25);
var g = Math.floor((b-f+1) / 3);
var h = (19*a + b - d - g + 15) % 30;
var i = Math.floor(c/4);
var j = c % 4;
var k = (32 + 2*e + 2*i - h - j) % 7;
var m = Math.floor((a + 11*h + 22*k) / 451);
var month = Math.floor((h + k - 7*m + 114) / 31);
var day = ((h + k - 7*m +114) % 31) + 1;

calc.month.value = easterM[month-3];
calc.day.value = day;
return false;
}

We now save this as an external Javascript (I'll call it easter.js).

The next step is to link this Javascript function into the page with the form so that we can link the button to the calculation.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.