Does anybody knows why this HTML/script generates a NaN undefined error?

This code is for Sales Tax calculation, base on a percent selection dropdown box.

If I enter the amount and click calculate, I get the NaN undefined error. I think that the issue is that the number totalAmount variable is interpreted as a string.

<!DOCTYPE html>
<html>
<head>
<h2>Sales Tax</h2>
</head>
<body>
<select id="ivu" name="ivu" class="drpdwni-content">
    <option href="#7" value=7>7</option>
    <option href="#11.5" value=11.5>11.5</option>
  </select>

<p id="outrig" ></p>

<div class=subContainer>
<form action="/action_page.php">
  <label for="subTotal">SubTotal</label>
  <input type="number" step="0.01" min=0 id="sub" name="sub" class="calculate" placeholder="SubTotal...">
  
<input type="submit" value="Calculate" onclick="myFunction()">
</form>
</div>

<script type="text/javascript">
function myFunction() {
var subTotal = document.getElementById("sub").value
var per = document.getElementById("ivu").value

// I think that the issue maybe is the number variable totalAmount interpreted as string
var sub = subTotal
var ivu = per / 100
var totalIvu = ivu * sub
var totalAmount = totalIvu + sub

// To get totalAmount formated $#,###.##
var totalAmount = formatDollar(totalAmount)

document.getElementById("outrig").innerHTML = per + "%<br>" + sub + "<br>" + totalIvu + "<b>" + totalAmount + "</b>"


function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num=="-" ? acc : num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}
</script>
</body>
</html> ```

Hi Richard,
You are right. totalAmount will be a string in this case.
On top of the issue you see, it also means that the + operator will do string concatination instead of arithmetic addition.
To solve this, replace the first 2 rows in myFunction with this:

var subTotal = parseFloat(document.getElementById("sub").value)
var per = parseFloat(document.getElementById("ivu").value)

Thanks yehudab, but the solution was convert the variable subTotal to number.

var sub = Number(subTotal)

With your suggestion, I get both fields NaN.undefined

Thanks again!

1 Like