Getting NaN as a result from Javascript - javascript

JS code
'use strict';
$(document).ready(function() {
});
function calculatePPI(inputWidth, inputHeight, inputDiagonal) {
document.getElementById("outputPPI").innerHTML=
((Math.sqrt(Math.pow('inputWidth', 2)) + (Math.pow('inputHeight', 2)))/'inputDiagonal');
}
HTML code
<body>
<h2>Length Converter</h2>
<p>The following program will convert your centimeters to inches.</p>
<p>
<label>Width (Pixels):</label>
<input id="inputWidth" type="number" placeholder="Width">
<p>
<label>Height (Pixels):</label>
<input id="inputHeight" type="number" placeholder="Height">
</p>
<p>
<label>Diagonal (Pixels):</label>
<input id="inputDiagonal" type="number" placeholder="Diagonal Length">
</p>
<button onclick="calculatePPI(document.getElementById('inputWidth', 'inputHeight', 'inputDiagonal').value)">Calculate</button>
</p>
<p>PPI: <span id="outputPPI"></span></p>
</body>
I'm getting NaN as a result whenever I try to calculate it.
Could anyone help me with this? I'm not sure where exactly the code is messing up, as I'm new to coding Javascript.

You can't use getElementById like that and in your function don't put a '' around your function variable.
Use like this:
'use strict';
$(document).ready(function() {
});
function calculatePPI(inputWidth, inputHeight, inputDiagonal) {
document.getElementById("outputPPI").innerHTML=
((Math.sqrt(Math.pow(inputWidth, 2)) + (Math.pow(inputHeight, 2)))/inputDiagonal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Length Converter</h2>
<p>The following program will convert your centimeters to inches.</p>
<p>
<label>Width (Pixels):</label>
<input id="inputWidth" type="number" placeholder="Width">
<p><label>Height (Pixels):</label>
<input id="inputHeight" type="number" placeholder="Height"></p>
<p><label>Diagonal (Pixels):</label>
<input id="inputDiagonal" type="number" placeholder="Diagonal Length"></p>
<button onclick="calculatePPI(document.getElementById('inputWidth').value, document.getElementById('inputHeight').value, document.getElementById('inputDiagonal').value)">Calculate</button>
</p>
<p>PPI: <span id="outputPPI"></span></p>
</body>

In this line (Math.sqrt(Math.pow('inputWidth', 2)) + (Math.pow('inputHeight', 2)))/'inputDiagonal'); the result is NaN because your doing math with strings. Remove the ' (single quotes).
(Math.sqrt(Math.pow(inputWidth, 2)) + (Math.pow(inputHeight, 2)))/inputDiagonal);
This should work, because now your accessing the actual value of the variables inputWidth, inputHeight, etc. Before you were just creating strings.

HTML
<h2>Length Converter</h2>
<p>The following program will convert your centimeters to inches.</p>
<p>
<label>Width (Pixels):</label>
<input id="inputWidth" type="number" placeholder="Width">
<p><label>Height (Pixels):</label>
<input id="inputHeight" type="number" placeholder="Height"></p>
<p><label>Diagonal (Pixels):</label>
<input id="inputDiagonal" type="number" placeholder="Diagonal Length"></p>
<p>
<button onclick="calculatePPI();">Calculate</button>
</p>
<p>PPI: <span id="outputPPI"></span></p>
Javascript
'use strict';
$(document).ready(function() {
});
function calculatePPI() {
var inputWidth = document.getElementById('inputWidth').value;
var inputHeight = document.getElementById('inputHeight').value;
var inputDiagonal = document.getElementById('inputDiagonal').value;
var outputPPI = document.getElementById("outputPPI");
outputPPI.innerHTML= ((Math.sqrt(Math.pow(inputWidth, 2)) + (Math.pow(inputHeight, 2)))/inputDiagonal);
}
Note: there lots of syntax error in code like the assignment of value in the calculation of PPI and in function value for the parameters.You can try above code your calculation with native javascript and below one for JQuery.
function calculatePPI() {
var inputWidth = $('#inputWidth').val();
var inputHeight = $('#inputHeight').val();
var inputDiagonal = $('#inputDiagonal').vval();
var outputPPI = $("#outputPPI");
outputPPI.html(((Math.sqrt(Math.pow(inputWidth, 2)) + (Math.pow(inputHeight, 2)))/inputDiagonal));
}

JavaScript return NaN when you are not calculating with valid Numbers
NaN = Not A Number
Make sure your operands are valid number in your equation.
You can try like -
<button onclick="calculatePPI('inputWidth','inputHeight','inputDiagonal')">Calculate</button>
function calculatePPI(inputWidth, inputHeight, inputDiagonal) {
inputWidth = document.getElementById(inputWidth).value
inputHeight = document.getElementById(inputHeight).value
inputDiagonal = document.getElementById(inputDiagonal).value
inputWidth = inputWidth ? inputWidth : 0; /*Setting default value 0*/
inputHeight = inputHeight ? inputHeight : 0; /*Setting default value 0*/
inputDiagonal = inputDiagonal ? inputDiagonal : 0; /*Setting default value 0*/
document.getElementById("outputPPI").innerHTML = ((Math.sqrt(Math.pow(inputWidth, 2)) + (Math.pow(inputHeight, 2)))/inputDiagonal);
}

Related

Decimal / Thousand separator (dot and comma) in the calculation results Js and Input field

I'm trying to get separators for thousands, hundreds and decimals in the input field. For example: if I calculate 50 * 50 the result is 2500 while I would like to get 2.500,00
Otherwise: if I calculate 52,5 * 52,5 the result is 2756.25, while I would like to get 2.756,25
Below is the code I worked out helping me with stackoverflow posts https://jsfiddle.net/snake93/dyepq135/10/
I'm a fan and don't even know the basics of coding, so I was just trying to figure out how to implement the separators (dot and comma).
<label class="mts-label">Peso</label>
<input type="number" step="any" class="mts-field" maxlength="4" id="peso" name"peso1" placeholder="es: 70Kg"/>
<label class="mts-label">Altezza</label>
<input type="number" class="mts-field" maxlength="4" id="altezza" name"altezza1" placeholder="es: 170cm"/>
<label class="mts-label">BMR</label>
<input type="text" class="mts-field" id="bmruomo" name="bmruomo"
placeholder="0.000,0 Kcal" min="1" readonly/>
<button onclick="calculate()">Calcola</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function() {
var peso = document.getElementById('peso').value;
var altezza = document.getElementById('altezza').value;
var bmruomo = parseFloat(peso * altezza);
document.getElementById('bmruomo').value = bmruomo;
}
function resetFields(){
var inputArray = document.querySelectorAll('input');
inputArray.forEach(function (input){
input.value = "";
});
}
You can do that...
const
f_BMR = document.forms['f-BMR']
, num2strEUR = n =>
{
let str = n.toFixed(2).replace('.',',')
return [...str].reduce((r,c,i,a)=>
{
r += c
let p = (a.length - i)
if ((p%3)===1 && p>4) r += '.'
return r
},'')
}
f_BMR.onsubmit = e =>
{
e.preventDefault()
let bmr_val = (f_BMR.peso1.valueAsNumber * f_BMR.altezza1.valueAsNumber)
f_BMR.bmruomo.value = num2strEUR(bmr_val )
}
label,input, div {
display : block;
float : left;
clear : both;
}
label, div{
font-size : .7em;
font-weight : bold;
margin-top : .8em;
}
label:after {
content : ' :'
}
<form name="f-BMR">
<label>Peso</label>
<input name="peso1" type="number" step="any" placeholder="es: 70Kg" value="" required>
<label>Altezza</label>
<input name="altezza1" type="number" step="any" placeholder="es: 170cm"/ value="" required>
<label>BMR</label>
<input name="bmruomo" type="text" class="mts-field" placeholder="0.000,0 Kcal" value="" readonly>
<div>
<button type="submit">Calcola</button>
<button type="reset">Reset</button>
</div>
</form>

Javascript: Real time calculations in a form

Using JavaScript I am working on a form that calculates in real time someone's BMI and TBW based on weight and height inputs.
I am using a addEventListener and onkeyup. I am very new to JavaScript, so bear with me.
What am I doing wrong?
Update: I have followed advice and replaced the "onkeyup" event with "oninput", and have put the height and weight values within the functions. I have also added .value. I am still have issues though.
<body>
<form id="adime-form" name="adime" method="post">
<div class="three-column clear">
<label for="">Age</label>
<input type="number" name="age" id="age"> <!--Input-->
</div>
<div class="three-column">
<label for="">Sex</label>
<input type="text" name="sex" id="sex"><!--Input-->
</div>
<div class="three-column">
<label for="">Height</label>
<input type="number" name="height" id="height"><!--Input-->
</div>
<div class="three-column">
<label for="">Weight</label>
<input type="number" name="weight" id="weight"><!--Input-->
</div>
<div class="three-column">
<label for="">BMI</label>
<input type="text" name="bmi" id="bmi" oninput="returnBmi"><!--Output-->
</div>
<div class="three-column">
<label for="">Total Body Water</label>
<input type="text" name="tbw-perc" id="tbw-perc" oninput="returnTbw"><!--Output-->
</div>
</form>
<script>
var getAge = document.getElementById("age");
var getSex = document.getElementById("sex");
document.getElementById("bmi").addEventListener("input", returnBmi);
document.getElementById("tbw-perc").addEventListener("input", returnTbw);
function returnBmi(){
var getHeight = document.getElementById("height").value;
var getWeight = document.getElementById("weight").value;
var getBmi = getWeight / (getHeight**2) * 703;
document.getElementById("bmi").innerHTML = getBMI;
}
function returnTbw(){
var getHeight = document.getElementById("height").value;
var getWeight = document.getElementById("weight").value;
var getTbw = -2.097 + 0.1069 *( getHeight * 2.54) + 0.2466 * (getWeight * .45);
document.getElementById("tbw-perc").innerHTML = getTbw;
}
</script>
enter code here
Consider using the 'input' event on the inputs: document.getElementById("bmi").addEventListener("input", returnBmi);
Also, take the Weight and Height values, INSIDE the update function:
function returnBmi(){
var getHeight = document.getElementById("height").value;
var getWeight = document.getElementById("weight").value;
var getBmi = getWeight / (getHeight**2) * 703;
document.getElementById("bmi").innerHTML = getBMI;
}
As you need to extract the values when the event is triggered.

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

What am I missing in my JavaScript code?

I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>

Failure to calculate the total monthly payment for a car loan. What's going wrong?

Updated code. calculate() still not working. The monthly payment amount is ultimately not being passed to the "total" id box. Does anyone see what the underlying problem is here? My syntax seems to be correct, I believe there may be a problem with my specification of where each variable is applied in the code.
I am having problems getting the function calculate() to pass the correct result in "total." Any possible solutions? The action of clicking the calculate button should display the total, but is displaying nothing at all, as if the button does not activate the calculate function at all.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr>
<form name id="Main">
<input type="number" id="price" placeholder="Price of the Car"/>
<br>
<br>
<input type="number" id="DP" placeholder="Down Payment"/>
<br>
<br>
<input type="number" id="R" placeholder="Annual % Rate"/>
<br>
<br>
<input type="number" id="N" placeholder="# of Years Loaned"/>
<br>
<br>
<input type="button" id="calculate" value="Calculate" onclick="javascript:calculate();"/>
<br>
<br>
<input type="number" id="total" placeholder="Total Cost..." readonly=""/>
<br>
<br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</html>
Use Math.pow() function instead. The ^ operator is not for mathematical power operations (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow).
Also, It's result.value = m, not the other way around :)
Also 2: R and M seem undefined to me, you have to initialize those variables with something, like you did with P and D.
Also 3: use chrome dev tools or anything like that. It will make your life much easier. Remember, javascript doesn't mean "no IDE" :D
Unfortunately, your original code will never work, as it has too many errors.
Here is the corrected fiddle for you, please, have a look:
http://jsfiddle.net/q330fqw8/
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;
}
I removed id="calculate" in HTML, because of this: Why JS function name conflicts with element ID?
In Javascript, the 4 variables P,D,R,N should be set properly. Finally, this m.value = result; -> result.value = m;
but I guess, you've already corrected some errors in the question. I worked with your original code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr/>
<form id="Main">
<input type="number" id="price" placeholder="Price of the Car" />
<br />
<br/>
<input type="number" id="DP" placeholder="Down Payment" />
<br/>
<br/>
<input type="number" id="R" placeholder="Annual % Rate" />
<br/>
<br/>
<input type="number" id="N" placeholder="# of Years Loaned" />
<br/>
<br/>
<input type="button" value="Calculate Monthly Payment" onclick="calculate();" />
<br/>
<br/>
Total Monthly Payment:<input type="number" id="total" placeholder="Total Cost..." readonly="" />
<br/>
<br/>
<input type="reset" value="Reset" />
</form>
<hr/>
</div>

Categories

Resources