In this exercise, you’ll make a couple of quick enhancement to the Miles Per Gal
ID: 3912988 • Letter: I
Question
In this exercise, you’ll make a couple of quick enhancement to the Miles Per Gallon application, like clearing the two entries if the user double-clicks in the Miles Per Gallon text box. Estimated time: 10 to 15 minutes.
2. Run the application to see that it works just like the one in the book. Then, in the JavaScript in the HTML file, note that there’s a clearEntries() function that isn’t used.
3. Enhance the application so the entries are cleared when the user double-clicks in the Miles Per Gallon text box. (Incidentally, this won’t work if the text box is disabled.)
4. Enhance the application so the Miles Driven text box is cleared when it receives the focus. Then, do the same for the Gallons of Gas Used text box.
5. Enhance the application so the calculation is done when the focus leaves the Gallons of Gas Used text box. To do the calculation, you just need to run the processEntries() function when that event occurs.
Explanation / Answer
Following is the answer:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script>
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var calculateMpg = function(miles, gallons) {
var mpg = (miles / gallons);
mpg = mpg.toFixed(1);
return mpg;
};
var processEntries = function() {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
} else if (miles <= 0 || gallons <= 0) {
alert("Both entries must be greater than zero");
} else {
$("mpg").value = calculateMpg(miles, gallons);
}
};
var clearEntries = function() {
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
};
var clearGallons = function() {
$("gallons").value = "";
};
var clearmiles = function() {
$("miles").value = "";
};
$("#mpg").dblclick(function(){
alert("The paragraph was double-clicked");
});
window.onload = function() {
$("calculate").onclick = processEntries;
$("miles").focus();
};
</script>
</head>
<body>
<main>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</main>
</body>
</html
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.