Question
In this exercise, youll upgrade a version of the MPG application so the error messages are displayed in span elements to the right of the
In this exercise, youll upgrade a version of the MPG application so the error messages are displayed in span elements to the right of the text boxes.
Open the HTML and JavaScript files in this folder: exercises_short\ch06\mpg\
Then, run the application and click the Calculate MPG button to see that an error message is displayed in an alert dialog box for each of the two input fields.
2. In the HTML file, add a span element after the input element for the first two text boxes.
3. Enhance the data validation so it displays the error messages in the span elements instead of in alert dialog boxes.
4. If the user entries are valid, clear the contents of the span elements.
5. If the user clicks the Clear Entries button, set the contents of each span element to an asterisk.
Current code:
HTML
Calculate MPG Calculate Miles Per Gallon
mpg.js
"use strict"; var $ = function(id) { return document.getElementById(id); }; function calculateMpg(miles, gallons) { var mpg = (miles / gallons); mpg = mpg.toFixed(1); return mpg; }; var processEntries = function() { var miles = $("miles").value; var gallons = $("gallons").value; var isValid = true; if (isNaN(miles) || miles false; } if (isNaN(gallons) || gallons false; } if (isValid) { $("mpg").value = calculateMpg(miles, gallons); } }; var clearEntries = function() { $("miles").value = ""; $("gallons").value = ""; $("mpg").value = ""; }; window.onload = function() { $("calculate").onclick = processEntries; $("clear").onclick = clearEntries; $("miles").ondblclick = clearEntries; $("miles").focus(); };
CSS:
body { font-family: Arial, Helvetica, sans-serif; background-color: white; margin: 0 auto; width: 700px; padding: 0 2em 1em; border: 3px solid blue; } h1 { color: blue; margin-bottom: .25em; } label { float: left; width: 11em; text-align: right; } input { margin-left: 1em; margin-right: .5em; margin-bottom: .5em; width: 11em; } span { color: red; }
Calculate Miles Per Gallon Miles Driven: Miles must be numeric and greater than zero Gallons must be numeric and greater than zero Gallons of Gas Used: Miles Per Gallon Calculate MPG Clear Entries
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started