Skip to content

Instantly share code, notes, and snippets.

@dennispipper
Created September 10, 2013 18:29
Show Gist options
  • Save dennispipper/6513518 to your computer and use it in GitHub Desktop.
Save dennispipper/6513518 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<!--From Murach's JavaScript and jQuery -->
<!--http://murach.com/books/qury/index.htm -->
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
// for versions IE 6-8
</script>
<script>
/*creates a function to get all of the objects the script needs - essentially a shortcut so that document.getElementById isn't typed over and over*/
var $ = function (id) {
return document.getElementById(id);
}
/*the user entries are parsed into miles and gallons*/
var calculateMpg = function () {
var miles = parseInt($("miles").value);
var gallons = parseFloat($("gallons").value);
var isValid = true;
/*testing for numbers only - no alpha allowed*/
if (isNaN(miles)) {
alert("Miles must be numeric");
}
else if (miles <= 0) {
alert("Miles must be greater than zero");
}
else if (isNaN(gallons)) {
alert("Gallons must be numeric");
}
else if (gallons <= 0) {
alert("Gallons must be greater than zero");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
/* clear function is called by the click event below and clears the values of the text boxes*/
var clear = function () {
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
}
/*creates and onload event that waits for the user to click the button and then calculates the MPG by running the calcualteMPG function*/
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("clear").onclick = clear;
$("miles").ondblclick = clear;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<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" disabled><br>
<label>&nbsp;</label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label>&nbsp;</label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment