Download magazine - Jonhoyle.com

Transcript
Adding Code
At this point, I recommend you download the completed project
< http://www.macfanatic.net/downloads/software/samplecode/mcJuly2007-make-a-widget.zip >
and follow along. The main reason is that all those text objects were given specific names and
the code references those names. You might not have changed the IDs (names) via the Inspector
and therefore your source list will have a lot of “Text1” and “Text2” and so forth. If the IDs
don’t match, the code won’t work. Basic HTML element accessing.
First, we’re going to add the main code that crunches the numbers. I have called this function
“calcTips(event)”. The basic design of this function is to grab number values from the three
Text Fields we put on the widget (one is on the back remember), error check those variables, do
the math, and place that number in the output area on the front of the widget. Most of the code is
related to error checking and rounding the number off to two decimal places, since we’re
working with money.
function calcTips(event) {
// Grab the decimal values from the input fields
var hours = parseFloat(document.getElementById("hours").value);
var tips = parseFloat(document.getElementById("tips").value);
var wageRate = parseFloat(document.getElementById("wageRate").value);
// If user hasn't entered any info, just return
// The isNaN(variable) is like checking for NULL
if ( isNaN(tips) || isNaN(hours) ) {
alert("User didn't enter enough info");
return;
}
// If user hasn't filled in the prefs on back, let them know
if ( isNaN(wageRate) || wageRate < 0 ) {
alert("User hasn't entered hourly wage");
document.getElementById("output").innerText = "Set Wage on Back!";
return;
}
// Calculate the actual rate
var out = ((hours * wageRate) + tips) / hours;
// Do the rounding to get to two decimal places
out = Math.round(out*100)/100;
var outString = out+''; // Converts out to a string by adding a empty space
if ( outString.indexOf('.') < 0 ) {
outString = outString + '.00'; // Add the decimal places for money :)
MPN, LLC Copyright 2003-2007
Page 15 of 126
Volume 5 Issue 7 July 2007