Simple JavaScript math not making sense - javascript

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

Related

Operators glitched? (JavaScript)

For some reason in my program, the + sign adds two digits together, in my code:
numerator1 += wholenumber1 * denominator1;
If wholenumber1 is 1 and denominator1 is 4, then the numerator1 is 14... I found this out by:
console.log(numerator1);
This is using inputs with type="number", and the other parts of the equation are working just fine... But this part is essential in order for my program to run properly, and help is greatly appreciated!
Though the input type is number, the actual value is of type string. You can check this by typeof operator. So you have to use functions like parseInt() to convert the value to integer in order to perform actual arithmetic operation.
console.log(typeof(document.getElementById('num1').value));
<input type="number" id="num1" value="1"/>
Code Example:
var numerator1 = 0;
var wholenumber1, denominator1;
wholenumber1 = document.getElementById('wholenumber1').value;
denominator1 = document.getElementById('denominator1').value;
numerator1 += parseInt(wholenumber1) * parseInt(denominator1);
console.log(numerator1);
wholenumber1: <input type="number" value="1" id="wholenumber1" /> <br/>
denominator1: <input type="number" value="4" id="denominator1" />
You need to convert the input into integers for this to work.
You can use use numerator1 += parseInt(wholenumber1) * parseInt(denominator1);
Refer to This for more

Javascript calculation from form data returns NaN

I'm fairly new to JS and I think there's a problem with my code in the parts where I'm using Javascript for arithmetic. If someone could show me where I went wrong I'd be very grateful! Currently, everything works except it returns NaN when the calculate button is clicked.
HTML:
<form>
AGE:<br><input id="Age" data-wrapper-class="inputBox" type="text" name="Age"><br>
</form>
<form>
HEIGHT (FEET):<br><input id="Feet" data-wrapper-class="inputBox" type="text" name="Feet"><br>
</form>
<form>
HEIGHT (INCHES):<br><input id="Inches" data-wrapper-class="inputBox" type="text" name="Inches"><br>
</form>
<form>
WEIGHT (POUNDS):<input id="Pounds" data-wrapper-class="inputBox" type="text" name="Pounds"><br>
</form>
<button id="calcButton" class="ui-btn ui-btn-b">Calculate BMR</button>
</div>
<div id="resultsInfo">
<p id="results"></p>
</div>
Javascript / jQuery:
$("#calcButton").click(function() {
var age = document.forms["Age"];
var feet = document.forms["Feet"];
var inches = document.forms["Inches"];
var wip = document.forms["Pounds"];
var feetInches = feet * 12;
var heightInches = feetInches + inches;
var weightMen = 6.23 * wip;
var heightMen = 12.7 * heightInches;
var ageMen = 6.8 * age;
var one = 66 + weightMen;
var two = one + heightMen;
var menBMR = two - ageMen;
$("#Calculator").hide();
parseFloat(document.getElementById("results").innerHTML = menBMR);
$("#resultsInfo").show();
});
As Jaromanda mentioned, you need to ensure the values are actually a Number value. Once they're a number type then you can do arithmetic operations on them. Here's why this matters:
var str = "12" // Number value
var num = 12 // String value
console.log(str * 2) // 1212
console.log(num * 2) // 24
In your code example, it looks as if you used inputs that are gathering the type="text" which means the values that you get from it would give you a String value. You can convert them to a number using parseInt or parseFloat, or you can change the HTML input type to type="number", I believe.

How to group together HTML5 Range Slider values?

Is there a way to group together multiple html5 slider fields. Originally I tried doing this will type=number fields but I didn't like the way it looked.
So what I what I have is 7 fields that I want to use sliders with individual min values of 0 and max values of 100 - however - the trick is that I need a way to add them all up to make sure in total they equal 100. None of the fields individually are required. Does that make sense?
Here is the function I tried but its not working at all:
<script>
function percentageTest() {
// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;
var x = (a + b + c + d + e + f + g);
// grouping together and doing the math
if (x != 100) {
text = "The total percentage must equal 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>
You can do something like this (just make it pretty and adapt it to your needs):
HTML
<form>
<formgroup class="ranges">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
<input type="range" min="0" max="100">
</formgroup>
</form>
JavaScript
var ranges = Array.from(document.querySelector('.ranges').children);
var total = ranges.reduce(function(acc, curr) {
return acc + Number(curr.value)
}, 0)
// Now you can check total
#Dave Gomez answers is way more elegant, please use it instead. But if you are wondering why it wasn't working :
Your document.getElementById("cuts").value; return strings. You need to convert them to int before adding them. This can be done like this :
a = +document.getElementById("cuts").value;
b = +document.getElementById("burns").value;
... etc

Why doesn't Javascript put some respeck on my input value?

I'm currently working on a budget software and I've come across this strange bug. First of here is my code:
<label class="label label-success">Choose your budget</label><br/><br/>
<div class="input-group-addon">€</div>
<input type="number" min="10" max="25000" maxlength="5" step="10" class="form-control" id="Input-budget" placeholder="Amount" onkeyup="this.value=this.value.replace(/[^\d]/,'')" onchange="budCalculate(this.value)">
this is the output line:
<li>
<strong>
Total cost: <span id="cost_eur">€0.00 </span> (<span id="cost_usd" class="small">$0.00</span>)
</strong>
</li>
Here is the Javascript:
function budCalculate(budget_amount) {
var budget = budget_amount;
cost_eur.innerHTML = "€"+((budget).toFixed(2);
cost_usd.innerHTML = "$"+ (budget * 1.13 ).toFixed(2);
}
It's supposed to put the value of the input on the output line.
The onkeyup is to prevent people from typing letters.
I've tried all kinds of variations and the funny thing is almost the same identical code is working on a similar looking page.
Why doesn't JavaScript put respeck on my value?
I suspect the issue is that budget is not a Number Object. this.value will pass a String Object. I would advise changing your function:
function budCalculate(budget_amount) {
var budget = 0;
console.log(typeof budget_amount);
budget = parseFloat(budget_amount);
cost_eur.innerHTML = "€" + budget.toFixed(2);
cost_usd.innerHTML = "$" + ( budget * 1.13 ).toFixed(2);
return budget;
}
You can now see what type of object is being passed. The parseFloat() should correct the issue.
Working Example: https://jsfiddle.net/Twisty/bqjg50sb/

javascript function Math.pow taking decimal value from an input text

I searched a lot on the web on this, but I've not found anything that would help me.
I did this:
montante <input type='text' id='A' onkeyup='calcola()' value='15000' /><br />
tasso <input type='text' id='i' onkeyup='calcola()' value='0.07' /><br />
anni <input type='text' id='n' onkeyup='calcola()' value='6' />
<script>
var A = document.getElementById('A').value;
var n = document.getElementById('n').value;
var float i = document.getElementById('i').value;
var R = A / ((1 - Math.pow((1 + i), -n)) / i);
document.write(R);
</script>
This works well if you declare the three variables normally, but if you take the values from an input the script does not give the correct answer...
I think the problem is in the function Math.pow that does not recognize the "i" var as a number cause of the dot in the input...
I need this working with the inputs, any help?
Thanks in advance
The type of the value that is read from your html input-elements will be determined by javascript as a String.
If you use the + operator on a variable of type number and a variable of type String, Javascript will perform a string-concatenation:
var a = "1";
var b = 2;
var c = a + b;
Var c will get the value: "12"
To prevent this behavior you have to to parse the value of your input first. You can do this by using the Javascript parseFloat() function.

Categories