What is wrong with my JavaScript?
<?xml version = "1.0" encoding ="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
...
<body>
<p>
<a href="http://nova.umuc.edu/~ct386a28/handson/index.html">Main Page</a>
</p>
<h1>GAS MILEAGE CALCULATOR</h1>
<form action="" method="post">
<script type = "text/javascript">
function mileageCalculator (beginMil, endMil, galCons, form)
{
var bM = parseFloat(beginMil);
var eM = parseFloat(endMil);
var gC = parseFloat(galCons);
if((eM<0)||(bM<0)||(gC<0))
{
alert("ERROR: One or more input(s) is negative.");
form.begMileage = " ";
form.endMileage = " ";
form.galConsumed = " ";
}
else if ((eM == 0) || (gC == 0))
{
alert("ERROR: The end mileage and/or gallon input is zero.");
form.begMileage = " ";
form.endMileage = " ";
form.galConsumed = " ";
}
else if (eM < bM)
{
alert("ERROR: End mileage is less than begining mileage.");
form.begMileage = " ";
form.endMileage = " ";
form.galConsumed = " ";
}
else
{
form.mpg.value = ((bM - eM) / gC);
}
}
</script>
<div class = "center">
<h3>Enter beginning mileage:</h3>
<input type="text" name ="begMileage" tabindex="1" />
<br />
<h3>Enter ending mileage:</h3>
<input type="text" name ="endMileage" tabindex="2" />
<br />
<h3>Enter gallons consumed:</h3>
<input type="text" name ="galConsumed" tabindex="3" />
<br />
<h2>TOTAL MILES PER GALLON</h2>
<input type="text" name ="mpg" tabindex="4" /> <br />
</div>
<p><br /></p>
<p>
<br /><input type="submit" value="SUBMIT" onclick = "mileageCalculator"/> <input type="reset" value="CLEAR"/> <br />
</p>
</form>
You can’t just submit a form to a function. You will have to get the form field values using some DOM method and pass it into your function. And vice versa, you have to access the form field you want to output to and set the value.
Even though this is a bit out of date, this follows your pattern nicely.
http://www.javaworld.com/jw-06-1996/jw-06-javascript.html