NaN confusion

I have the form

<form id="tax_form" name="tax_form">
    <label for="User_Name">Name:</label>
    <input type="text" id="User_Name" required>
    <label for="Quantity">Quantity</label>
    <input type="number" id="Quantity" value="3">
    <label for="Price">Price</label>
    <input type="number" id="Price" value="5.31" step="0.01">
    <label class="total">Total</label>
    <input type="text" id="Total" readonly>
    <input type="submit"> 
</form>

and the script

<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>

but when i submit it I get


I dont understand why its NaN (there number data types in the form) so how can I get the calculations to work?

Thanks…

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.

Two minor amendments to the code fix the problem:

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);
  1. Don’t start a number with a decimal point - add a zero in front.
  2. 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).
1 Like

ok, what does event.preventDefault() do?

There’s a little reading on it here at the MDN

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.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.