Java Reference
In-Depth Information
exercise 1 Solution
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 11: Question 1</title>
</head>
<body>
<form action="" name="form1">
<p>
<input type="text" name="txtCalcBox" value="0.0" />
</p>
<input type="button" value="Convert to centigrade"
id="btnToCent" name="btnToCent" />
</form>
<script>
function convertToCentigrade(degFahren) {
var degCent = 5 / 9 * (degFahren - 32);
return degCent;
}
function btnToCentClick() {
var calcBox = document.form1.txtCalcBox;
if (isNaN(calcBox.value) == true ││ calcBox.value == "") {
calcBox.value = "Error Invalid Value";
} else {
calcBox.value = convertToCentigrade(calcBox.value);
}
}
document.getElementById("btnToCent")
.addEventListener("click", btnToCentClick);
</script>
</body>
</html>
Save this as ch11 _ question1.html .
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 a click event listener
that executes btnToCentClick() when the event fires.
The first line of btnToCentClick() declares a variable and sets it to reference the object representing
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.
Search WWH ::




Custom Search