ARTICLE AD BOX
The reason * works but + doesn't comes down to how JavaScript handles types. .value on an HTML input always returns a string, even when the input type is number. The * operator can only mean one thing in JavaScript (multiplication), so it automatically converts both sides to numbers for you. But + is overloaded to do both addition and string concatenation, so when JavaScript sees two strings, it concatenates them instead of adding.
The fix is to convert the values explicitly using Number() or parseFloat(), but it needs to wrap .value specifically: Number(document.getElementById("unloadedtotal").value)
The subtotal line would look like this:
document.getElementById("subtotal").value = Number(document.getElementById("unloadedtotal").value) + Number(document.getElementById("locktotal").value);New contributor
mokayG is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
The issue is that .value always returns a string, even on <input type="number"> elements. The * operator automatically coerces strings to numbers, but + does string concatenation when either operand is a string.
document.getElementById("subtotal").value = Number(document.getElementById("unloadedtotal").value) + Number(document.getElementById("locktotal").value);Alternatively, you can use parseFloat() or prefix with + (the unary plus operator):
// parseFloat approach parseFloat(document.getElementById("unloadedtotal").value) + parseFloat(document.getElementById("locktotal").value) // unary + approach +document.getElementById("unloadedtotal").value + +document.getElementById("locktotal").valueAny of these three will force both operands to numbers before the + runs, giving you actual addition instead of concatenation.
Explore related questions
See similar questions with these tags.
