I was tutoring some high schoolers today (not a regular gig, was an accident) on javascript and ended up spending a quick 20 minute lunch break on doing their assignment. Here is a very simple example of a Mileage Calculator using Javascript and the Document Object Model (DOM). See it in action here.
<!DOCTYPE html> <html> <head> <style type="text/css"> h2 { color:green; } </style> <meta charset=utf-8 /> <title>Simple Javascript Mileage Calculator</title> <script> function calculateMpg() { // variables var milesDriven = document.getElementById("miles_driven").value; var gallonsUsed = document.getElementById("gallons_used").value; var pricePerGallon = document.getElementById("price_per_gallon").value; // input validation if (milesDriven <= 0 || gallonsUsed <= 0 || pricePerGallon <= 0) { alert("Please enter a value higher than 0!"); formReset(); } else { var mpgCost = milesDriven / gallonsUsed; var costOfTrip = pricePerGallon * gallonsUsed; } // if "undefined" set to 0 if (mpgCost === undefined || costOfTrip === undefined) { mpgCost = 0; costOfTrip = 0; } // parse and format the output var pmpg = parseFloat(mpgCost).toFixed(2); document.getElementById("your_mpg").innerText = pmpg; var pcot = parseFloat(costOfTrip).toFixed(2); var output = "$" + pcot; document.getElementById("cost_of_trip").innerText = output; } // function to reset the form and fields function formReset() { document.getElementById("your_mpg").innerText = 0; document.getElementById("cost_of_trip").innerText = 0; document.getElementById("mileage_form").reset(); } // initialize function init() { document.getElementById("calculate").onclick = calculateMpg; } window.onload = init; </script> </head> <body> <h1 id="header">Calculate your MPG</h1> <h4 id="subheader">Enter the information below to see if you are getting good mileage!</h4> <form id="mileage_form"> <label for="miles_driven">Miles Driven:</label> <input type="text" name="miles_driven" id="miles_driven"> <br /> <br /> <label for="gallons_used">Gallons of Gas Used:</label> <input type="text" name="gallons_used" id="gallons_used"> <br /> <br /> <label for="price_per_gallon">Price per gallon:</label> <input type="text" name="price_per_gallon" id="price_per_gallon"> <br /> <br /> <input type="button" value="Calculate the MPG and Cost of the Trip" id="calculate"></input> <br /> <br /> <input type="button" value="Clear form" onclick="formReset()"></input> <br /> <br /> <h3>Your MPG:</h3> <h2 id="your_mpg"></h2> <h3>The Cost of the Trip is: </h3> <h2 id="cost_of_trip"></h2> </form> <script> </script> </body> </html>
Recent Comments