Calculator Tutorial5. Calculate Function |
|
Join the DiscussionMore of this FeatureGetting Started Convert to Javascript Test the Javascript Create the Form 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 calc = document.getElementById('ecalc'); 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. There is also a version of this tutorial that uses unobtrusive JavaScript. |


