I feel like I'm a novice again. I thought I was long past these problems. below is a simple script with two function neither of which work. What am I missing. Any help appreciated.
function calculator() { var bee = document.getElementById("beerPerc").value; var win = document.getElementById("winePerc").value; var liq = 100 - (bee + win); document.getElementById("liquorPerc").value = liq; } function calculator2() { document.getElementById("liquorPerc").value = parseInt(100 - (document.getElementById("beerPerc").value + document.getElementById("winePerc").value)) }
<div id="calcArea"> <div> <input type="number" id="beerPerc" value="50" onkeyup="calculator2()"> % of Beer Drinkers<br> <input type="number" id="winePerc" value="30" onkeyup="calculator2()"> % of Wine Drinkers<br> <input type="number" id="liquorPerc" onkeyup="calculator2()"> % of Liquor Drinkers<br> </div> </div>
Two things:
Case is significant. If you declare the variable bee
, you can't read it with Bee
.
.value
is always a string. You need to convert the strings to numbers:
var bee = Number(document.getElementById("beerPerc").value);
If you don't do this, +
will perform string concatenation, not addition.
You don't need to call parseInt()
on the result of a numeric calculation, that's always a number.
function calculator2() {
document.getElementById("liquorPerc").value = 100 - (parseInt(document.getElementById("beerPerc").value, 10) + parseInt(document.getElementById("winePerc").value, 10)))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.