<script>
var calculateTax = function(event) {
event.preventDefault();
var price = document.getElementById("Price").value;
var quantity = document.getElementById("Quantity").value;
var tax = .0825;
var tax_total = (price * tax);
var total = (price + tax_total) * quantity;
var total_price = "$"+ total.toFixed(2);
document.getElementById("Total").value = total_price
}
var form = document.getElementById('tax_form');
form.addEventListener('submit', calculateTax, false);
</script>
It looks like itâs seeing the pre-populated values as string values, not numbers. If you take those out, and enter your own numeric values, it calculates through.
That said, something is going wrong with the calculation - 10 items at 12 (units), should not come out at $1209.90, even allowing for tax. Interestingly, if you add decimal places to the âpriceâ input, that also generates a NaN result.
var calculateTax = function(event) {
event.preventDefault();
var price = document.getElementById("Price").value;
var quantity = document.getElementById("Quantity").value;
var tax = 0.0825;
var tax_total = (price * tax);
var total = (+price + tax_total) * quantity;
var total_price = "$"+ total.toFixed(2);
document.getElementById("Total").value = total_price;
};
var form = document.getElementById('tax_form');
form.addEventListener('submit', calculateTax, false);
Donât start a number with a decimal point - add a zero in front.
when adding a string to a number you need to convert the string to a number first before adding them together (a unary + is the shortest code to do this or pass it to the Number() function to be clearer what is happening).
it prevents the running of whatever action would occur by default if the JavaScript wasnât there
for example if the JavaScript is attached to a link then it prevents the browser going to wherever the href references and if it is attached to a form it prevents the form from being submitted.