Yesterday I submitted this problem, got terrific responses but my code still didn’t work. I modified my code based on another student’s code that works, but my code still won’t calculate but it validates in javascript. Any suggestions. This homework is due TONIGHT!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<title>Price Calculator</title>
<script type="text/javascript">
function fixOrder() {
const TAX = 0.975;
var numPrice;
var total;
var tax;
numPrice = parseFloat(document.getElementById("cost").value, 10);
tax = parseFloat(document.getElementById("tax").value, 10);
total = parseFloat(document.getElementById("total").value, 10);
numPrice = numPrice * TAX;
total = numPrice;
total = document.getElementById("total").value = "$" + total.toFixed(2);
if (isNaN(numPrice)) {
alert("Sorry,you must enter a numeric value to place order");
numPrice = 0;
}
}
</script>
</head>
<body bgcolor="#00f3F1">
<h1 align="left">Price Calculator</h1>
<form name="form" id="form">
<p>Price: <input type="text" id="cost" name="cost" value="" onchange=
"fixOrder" /></p>
<p>Tax: <input type="text" id="tax" name="tax" value="" onchange=
"fixOrder" /></p>
<p>Total: <input type="text" id="total" name="total" value="" disabled=
"disabled" /></p>
</form>
</body>
</html>
JS Fiddle
Your onchange event is
onchange="fixOrder"which is not really doing anything. If you change it tofixOrder()you will call the functionfixOrderwhen the change event is fired.Furthermore:
constis a reserved word in JavaScript. I don’t think JS has constants. You should change that line fromconst TAXtovar TAX;parseInt, which takes two arguments (string and base/radix),parseFloatonly takes one argument (string), so you can remove the, 10from itI imagine you want something like:
This will use the dollar amount of tax you enter, or if that doesn’t exist, it will use the constant rate that you have supplied at the beginning (this was changed from .975 to .0975).
Also, notice the new calculation from total, we’re taking the decimal part of the number, dividing it by 100 to get to two decimal places, reversing it back so it’s in the proper order again, and then rounding it to the nearest 1 (cent).
HTML Body: