Javascript variable displaying NaN - javascript

Can someone advise how I can get my final variable to display as a number (the value of my function variable) rather than NaN?
<form id="computeroi">
<fieldset>
<div class="col-1 pblue"> <p class="float-left"> 1. How many monthly visitors does your website get per month? </p> <input type="number" value="0" id="monthlyvisitors" class="width-50" onchange="computeroi()"> </div>
<div class="col-1 pblue"> <p class="float-left"> 2. How many of those visitors are from a mobile device? </p> <input type="number" value="0" id="mobilevisitors" class="width-50" onchange="computeroi()"> </div>
<div class="col-1 pblue"> <p class="float-left"> 3. What is your average deal worth ? </p> <input type="number" value="0" id="dealworth" class="width-50" onchange="computeroi()"> </div>
<div class="col-1 pblue"> <input type="submit" value="Submit" class="width-25" id="submit" width="25"> </div>
<div class="col-1 "> <h1 id="newdealw"> </h1> </div>
</fieldset>
</form>
function computeroi() {
var monthlyv = document.getElementById('monthlyvisitors').value;
var mobilet = document.getElementById('mobilevisitors').value;
var dealw = document.getElementById('dealworth').value;
var newdeals = (mobilevisitors / monthlyvisitors);
var newdealw = (newdeals * dealworth);
document.getElementById('newdealw').innerHTML = newdealw;
}

mobilevisitors,monthlyvisitors,dealworth isn't declared or defined anywhere in your method .
Rather your assign value of ids monthlyvisitors,mobilevisitors,dealworth into monthlyv ,mobilet ,dealw
var monthlyv = document.getElementById('monthlyvisitors').value;
var mobilet = document.getElementById('mobilevisitors').value;
var dealw = document.getElementById('dealworth').value;
Try like this
var monthlyv = document.getElementById('monthlyvisitors').value;
var mobilet = document.getElementById('mobilevisitors').value;
var dealw = document.getElementById('dealworth').value;
var newdeals = ( +mobilet / +monthlyv );
var newdealw = (newdeals * +dealw );
N:b: + sign before variable will consider it as a number.

var monthlyv = document.getElementById('monthlyvisitors').value;
var mobilet = document.getElementById('mobilevisitors').value;
var dealw = document.getElementById('dealworth').value;
var newdeals = (mobilevisitors / monthlyvisitors);
var newdealw = (newdeals * dealworth);
there are no mobilevisitors ,monthlyvisitors variables in your code.
also use parseInt() or parseFloat() accordingly before performing mathematical operations to be safe.

there are no mobilevisitors ,monthlyvisitors variables in your code.
juste change the last two lines like this:
var newdeals = (mobilet / monthlyv);
var newdealw = (newdeals * dealw);

You have not declared variable mobilevisitors or this one monthlyvisitors so you cannot get value. You should use the variable monthlyv and mobilet into which you are getting the value of these two thing (mobilevisitors and monthlyvisitors)

Related

JavaScript putting two variable's value into an array

i have two variables name and location which are provided by two <input type="text">. I need to get an outcome of Smith_California but I am getting an output of userName_userLoca in the console.
Any suggestions would help.
currently, I have:
HTML:
<form class="inputContainer" id="inputContainer" methed="post">
<label for="userNam">Your Name</label>
<input type="text" class="userNam" id="userNam" name="userNam" />
<label for="userLoca">Your Location</label>
<input type="text" class="userLoca" id="userLoca" name="userLoca" />
<button class="vButton" id="vButton" type="submit" onclick="testfun()">
Begin Test
</button>
</form>
Javascript:
var userName = document.getElementById('userNam');
var userLoca = document.getElementById('userLoca');
var userSID = ['userName', 'userLoca'];
console.log(userSID.join('_'));
Remove the quotes and use .value:
var userSID = [userName.value, userLoca.value];
You are accessing dom-element, using var userName = document.getElementById('userNam');.
Try with var userName = document.getElementById('userNam').value.
Also remove the quotes from var userSID = ['userName', 'userLoca']; and use it like below
var userSID = [userName, userLoca];

Bootstrap form outputting wrong results

Despite not being linked (to my knowledge), when inputting the Celsius number, the Fahrenheit formula will run and be implemented to the Celsius output, with the correct formula being outputted on the Fahrenheit output, and vice versa when inputting a Fahrenheit number.
Image
I have tried several if statements but they only seem to work for one of the outputs with the other having no value result at all.
**HTML//Bootstrap**
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">C°</span>
<input type="number" class="form-control" id="cAmount" placeholder="Celsius">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">F°</span>
<input type="number" class="form-control" id="fAmount" placeholder="Fahrenheit">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Celsius Temperature</span>
<input type="number" class="form-control" id="celsius-result" disabled>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Fahrenheit Temperature</span>
<input type="number" class="form-control" id="f-res" disabled>
</div>
</div>
**Javascript**
let formSubmit = document.querySelector('#tempCalculator')
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = celVal.toFixed(2);
fahResult.value = fahVal.toFixed(2);
//stop form refreshing
e.preventDefault();
}
Expected would be just to have one correct value appear in the corresponding output, this does happen, but an incorrect value appears in the unexpected output.
Here's a Codepen link for the full application: https://codepen.io/str-99/pen/NmwXJz
If I'm understanding you correctly this is one way to accomplish what you're trying:
let formSubmit = document.getElementById('tempCalculator');
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = Number(fahInput.value) > 0 ? celVal.toFixed(2) : '';
fahResult.value = Number(celInput.value) > 0 ? fahVal.toFixed(2) : '';
//reset input boxes
document.getElementById('cAmount').value = '';
document.getElementById('fAmount').value = '';
e.preventDefault();
}
The ternary operator works great for instances like this. We can simply change the value to an empty string when it's not the right/desired input. And for added measure clearing out the input boxes to 'reset' after each calculation.

Advice needed with Javascript and html form with numerical input & output

I am developing a web page for machinists and CNC programmers. There are a lot of formulas for various applications, and I am having trouble finding a way to output my JS code to a form. I am adding the code for one below. Any help would be appreciated, I'm stumped.
<title>Angle depth</title>
</head>
<body>
<form id="depth" >
<p>Angle Tool Depth Calculator</p>
<div>
<label for="toolAngleDeg">enter tool angle</label>
<input name="toolAngleDeg" id="toolAngleDeg" type="text"/>
</div>
<div>
<label for="finalDia">enter the diameter</label>
<input name="finalDia" id="finalDia" type="text"/>
</div>
<div>
<label for="zDepth">Depth</label>
<input name="zDepth" id="zDepth" type="text"/>
</div>
<div>
<input type="button" id="button01" value="calculate"/>
</div>
</form>
<script>
// prompted var
var toolAngleDeg = document.getElementById('toolAngleDegree');
var finalDia = document.getElementById('finalDia');
// calc var
var (toolAngleRad = ((parseFloat('toolAngleDeg') * Math.PI) / 180))
var (cTool = (.5 / (Math.tan(toolAngleRad / 2))));}
var depthZ = Math.round((cTool * parseFloat('finalDia') * 10000) / 10000).toFixed(4);
//output
function getDepth() {
document.getElementById("zDepth") = depthZ.value;
}
function calcDepth() {
var button1 = document.getElementById('button01');
button01.onclick = getDepth();
}
window.onload = calcDepth;
</script>
</body>
var toolAngleDeg = document.getElementById('toolAngleDegree');
Your variable toolAngleDeg is a DOM element not the value, you will get the value from toolAngleDeg.value. Same goes with all other input fields
parseFloat('toolAngleDeg')
Here you are trying to convert the string 'toolAngleDeg' to a number which will give you NaN, you should pass the variable there instead parseFloat(toolAngleDeg). Same goes with parseFloat('finalDia')
document.getElementById("zDepth") = depthZ.value
That should be
document.getElementById("zDepth").value = depthZ
There are a lot of problems with your code, see other answers.
Here is a working solution:
<form id="depth">
<p>Angle Tool Depth Calculator</p>
<div>
<label for="toolAngleDeg">enter tool angle</label>
<input name="toolAngleDeg" id="toolAngleDeg" type="text" />
</div>
<div>
<label for="finalDia">enter the diameter</label>
<input name="finalDia" id="finalDia" type="text" />
</div>
<div>
<label for="zDepth">Depth</label>
<input name="zDepth" id="zDepth" type="text" />
</div>
<div>
<input type="button" id="button01" onclick="calcDepth()" value="calculate" />
</div>
</form>
<script>
function calcDepth() {
// Save input values in variables
var toolAngleDeg = parseFloat(document.getElementById('toolAngleDeg').value);
var finalDia = parseFloat(document.getElementById('finalDia').value);
// Calculate depthZ
var toolAngleRad = (toolAngleDeg * Math.PI) / 180
var cTool = (.5 / (Math.tan(toolAngleRad / 2)));
var depthZ = Math.round((cTool * finalDia * 10000) / 10000).toFixed(4);
// Output depthZ
document.getElementById("zDepth").value = depthZ;
}
</script>
There were many issues in your code :
1 - var toolAngleDeg = document.getElementById('toolAngleDegree').value;
toolAngleDegree is not an id in your HTML document. toolAngleDeg is.
2 - var (toolAngleRad = ((parseFloat('toolAngleDeg') * Math.PI) / 180))
var ( is a syntax error.
parseFloat takes a string as a parameter. Not the id of a field. You should remove the single quotes.
3 - var (cTool = (.5 / (Math.tan(toolAngleRad / 2))));
var ( is still a syntax error
you're using too many parenthesis there
4 - Your getDepth function doesn't read the inputs value. So you are updating the value of the zDepth field with a variable that has not been recomputed with the new fields values.
you need to move the code where you're reading inputs values inside this function to compute whatever you're willing to compute.
5 - button01.onclick = getDepth();
Here, you are not adding getDepth as an event listener to the "click" event. You are adding invoking getDepth and setting its return value as an event listener. You should remove the parenthesis.
I fixed them for you in the snippet below :
//output
function getDepth() {
// prompted var
var toolAngleDeg = document.getElementById('toolAngleDegree').value;
var finalDia = document.getElementById('finalDia').value;
// calc var
var toolAngleRad = ((parseFloat(toolAngleDeg) * Math.PI) / 180);
var cTool = 0.5 / Math.tan(toolAngleRad / 2);
var depthZ = Math.round((cTool * parseFloat(finalDia) * 10000) / 10000).toFixed(4);
document.getElementById("zDepth").value = depthZ;
}
function calcDepth() {
var button1 = document.getElementById('button01');
button01.onclick = getDepth;
}
window.onload = calcDepth;
<title>Angle depth</title>
</head>
<body>
<form id="depth" >
<p>Angle Tool Depth Calculator</p>
<div>
<label for="toolAngleDeg">enter tool angle</label>
<input name="toolAngleDeg" id="toolAngleDegree" type="text"/>
</div>
<div>
<label for="finalDia">enter the diameter</label>
<input name="finalDia" id="finalDia" type="text"/>
</div>
<div>
<label for="zDepth">Depth</label>
<input name="zDepth" id="zDepth" type="text"/>
</div>
<div>
<input type="button" id="button01" value="calculate"/>
</div>
</form>
</body>

Simple JavaScript function returns function and not value

I'm just starting out and I'm trying to build a simple calculation function that will display the result of 2 numbers on a page. When the submit button is hit the output is the function and not the value. Where have I gone wrong?
HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
You have several issues with your javascript. Let's break them down one by one:
var price = function() {
parseFloat(document.getElementById("price"));
}
document.getElementById returns an element. parseFloat would try to calculate the element, and not the value in this case (Which would always be NaN or Not a Number). You want the value of this element, so using .value will return the value. Furthermore, you're not actually doing anything with the value. (You should use return to return the float found, or set it to another variable.)
var final = function() {
final = price * tax;
final = total
}
price and tax are both functions in this case. You can't simply multiply them to get your desired result. Using var total = price() * tax(); will set the variable total to the float returned from price() and tax() now. Returning this value to the function will fix the next line:
document.getElementById("output").innerHTML = final;
final here is also a function. You want to call it by using final().
Your final script:
var total = function() {
var price = function() {
return parseFloat(document.getElementById("price").value);
}
var tax = function() {
return parseFloat(document.getElementById("tax").value);
}
var final = function() {
var total = price() * tax();
return total
}
document.getElementById("output").innerHTML = final();
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
You have several issues, you put some code into function without calling them.
Another problem is, you need the value of the input tags.
'use strict';
var total = function() {
var price = parseFloat(document.getElementById("price").value);
// get value ^^^^^^
var tax = parseFloat(document.getElementById("tax").value)
// get value ^^^^^^
// calculate directly the final value
var final = price * tax;
document.getElementById("output").innerHTML = final;
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
<div id="output"></div>
Delete
var final = function() {
final = price * tax;
final = total
}
and instead put
return price * tax;

Why won't my JS function work properly?

I am very new to Javascript, so please pardon my lack of knowledge.
I am trying to use Javascript to find the slope of two data points (x1,y1)(x2,y2). The equation for the slope is m=y1-y2/x2-x1. Here is what I have done so far in JS fiddle: http://jsfiddle.net/1wvfz0ku/
The problem is that when I try to calculate the points only NaN appears.
Like I said I am very new at coding in JS, so I can't see where I have messed up in. Any help would be much appreciated! :-)
<!DOCTYPE html>
<html>
<body>
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<script>
function findSlope() {
//The points//
var xOne = document.getElementById("x1").value;
var xTwo = document.getElementById("x2").value;
var yOne = document.getElementById("y1").value;
var yTwo = document.getElementById("y2").value;
//slope equation//
var op1 = yTwo - yOne;
var op2 = xTwo - xOne;
var answer = op1 / op2;
document.getElementById("slope").innerHTML = answer;
}
function reset(){
document.getElementById("points","slope").reset();
}
</script>
<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
</div>
</body>
</html>
This works just fine unless xTwo - xTwo is 0, in which case you're trying to divide a number by 0, which is defined in JavaScript to be NaN.
That said: The value property of elements is always a string. It just happens that all of the operations you've used (-, /) will implicitly convert from string to number, but if you'd used + you'd've gotten some very odd results indeed (because + with strings is concatenation, not addition). Better to explicitly ensure you're dealing with numbers, by using parseInt(theString, 10) (if you're dealing with decimal).
Example allowing for xTwo - xOne being 0 and parsing the inputs as decimal:
function findSlope() {
//The points//
var xOne = parseInt(document.getElementById("x1").value, 10);
var xTwo = parseInt(document.getElementById("x2").value, 10);
var yOne = parseInt(document.getElementById("y1").value, 10);
var yTwo = parseInt(document.getElementById("y2").value, 10);
//slope equation//
var op1 = yTwo - yOne;
var op2 = xTwo - xOne;
var answer = op2 === 0 ? "flat or whatever" : op1 / op2;
document.getElementById("slope").innerHTML = answer;
}
function reset(){
document.getElementById("points","slope").reset();
}
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
http://www.w3schools.com/jsref/jsref_number.asp Use code x = Number(x) and do it for all variables

Categories

Resources