Question: Better MPG Modify the MPG application to include an entry that will clear values entered into the fields and give an error if the values
Better MPG
Modify the MPG application to include an entry that will clear values entered into the fields and give an error if the values are non-numeric or less than zero. This application will not calculate the miles per gallon for a Tesla.
code to modify:
mpg.js
"use strict";
const $ = selector => document.querySelector(selector);
const isInvalidValue = val => { if (isNaN(val)) { console.log("Value is not a number"); } else if (val <= 0) { console.log(`Value ${val} is not greater than zero.`); } return isNaN(val) || val <= 0 };
const focusAndSelect = selector => { const elem = $(selector); elem.focus(); elem.select(); };
const processEntries = () => { console.log("processEntries function has started");
// clear previous calculation $("#mpg").value = "";
const miles = parseFloat($("#miles").value); const gallons = parseFloat($("#gallons").value); console.log("miles = " + miles); console.log("gallons = " + gallons);
let errorMessage = "";
if (isInvalidValue(miles)) { errorMessage += "Miles driven must be a valid number greater than zero. "; focusAndSelect("#miles"); } if (isInvalidValue(gallons)) { errorMessage += "Gallons of gas used must be a valid number greater than zero."; focusAndSelect("#gallons"); } if (errorMessage == "") { console.error("The data is valid and the calculation is next"); const mpg = miles / gallons; console.error("mpg = " + mpg); $("#mpg").value = mpg.toFixed(2); } else { alert(errorMessage); } };
document.addEventListener("DOMContentLoaded", () => { $("#calculate").addEventListener("click", processEntries); $("#miles").focus(); });
mpg.css
body { font-family: Arial, Helvetica, sans-serif; background-color: white; margin: 0 auto; width: 600px; border: 3px solid blue; padding: 0 2em 1em; }
h1 { color: blue; }
div { margin-bottom: 1em; }
label { display: inline-block; width: 10em; text-align: right; margin-right: 0.5em; }
index.html
The Miles Per Gallon Calculator
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
