Java Reference
In-Depth Information
var calcBox = document.form1.txtCalcBox;
if (isNaN(calcBox.value) == true || calcBox.value == “”)
{
calcBox.value = “Error Invalid Value”;
}
else
{
calcBox.value = convertToCentigrade(calcBox.value);
}
}
</script>
</head>
<body>
<form action=”“ name=”form1”>
<p>
<input type=”text” name=”txtCalcBox” value=”0.0” />
</p>
<input type=”button” value=”Convert to centigrade”
name=”btnToCent” onclick=”btnToCent_onclick()” />
</form>
</body>
</html>
Save this as
ch07_q1.htm
.
The interface part is simply a form containing a text box into which users enter the Fahrenheit value
and a button they click to convert that value to centigrade. The button has its
onclick
event handler set
to call a function named
btnToCent_onclick()
.
The fi rst line of
btnToCent_onclick()
declares a variable and sets it to reference the object represent-
ing the text box.
var calcBox = document.form1.txtCalcBox;
Why do this? Well, in your code when you want to use
document.form1.txtCalcBox
, you can now
just use the much shorter
calcBox
; it saves typing and keeps your code shorter and easier to read.
So
alert(document.form1.txtCalcBox.value);
is the same as
alert(calcBox.value);
In the remaining part of the function you do a sanity check — if what the user has entered is a number
(that is, it is not
NotANumber
) and the text box does contain a value, you use the Fahrenheit-to-centigrade
conversion function you saw in Chapter 2 to do the conversion, the results of which are used to set the
text box's value.