Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

JavaScript Source Code


Welcome to Dream.In.Code
Become an Expert!

Join 244,285 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 975 people online right now. Registration is fast and FREE... Join Now!





Miles Per Gallon Calculator

A function to calculate gas mileage.

Submitted By: OliveOyl3471
Actions:
Rating:
Views: 1,159

Language: JavaScript

Last Modified: October 13, 2008
Instructions: Copy and paste the function into the document head. Copy and paste the form into the document body.

Snippet


  1. function calcMPG()
  2. {
  3.         var startMiles = document.forms[0].startingMileage.value;
  4.         var endMiles = document.forms[0].endingMileage.value;
  5.         var gallons = document.forms[0].gallonsUsed.value;
  6.        
  7.         if(isNaN(startMiles) || isNaN(endMiles) || isNaN(gallons))
  8.         {
  9.         window.alert("Each textbox must contain only numbers!");
  10.         }
  11.         else
  12.         {
  13.                 if(gallons > 0)
  14.                 {
  15.                 document.forms[0].milesPerGallon.value = ((endMiles - startMiles)/gallons).toFixed(1);
  16.                 }
  17.         }
  18. }
  19.  
  20. <body>
  21. <script type="text/javascript">
  22. document.write("<p><h2>Miles Per Gallon Calculator</h2></p>");
  23. document.write("<p><h5>To find miles per gallon, enter starting and ending mileage and gallons of gas used.</h5></p>");
  24. </script>
  25.         <form action ="">
  26.                 <p>Starting Miles:<br />
  27.                 <input type = "text" name = "startingMileage" value = "0" size = "10" onchange = "calcMPG()" /></p>
  28.                 <p>Ending Miles:<br />
  29.                 <input type = "text" name = "endingMileage" value = "0" size = "10" onchange = "calcMPG()" /></p>
  30.                 <p>Gallons Used:<br />
  31.                 <input type = "text" name = "gallonsUsed" value = "0" size = "10" onchange = "calcMPG()" /></p>
  32.                 <p>Miles Per Gallon:<br />
  33.                 <input type = "text" name = "milesPerGallon" value = "0" size = "10" /></p>
  34.         </form>       
  35. </body>
  36.  

Copy & Paste


Comments


BetaWar 2008-10-13 16:34:40

Note for use: You need to fill in the top 3 fields for the calculation to be done. Interesting snippet :)

OliveOyl3471 2008-10-13 16:46:41

Thank you!

jjsaw5 2008-10-13 20:34:42

very nice Olive!


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month