Why won't my JS function work properly? - javascript

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

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

Is there a way to multiply inputs when they begin with a decimal like this- .125 or even 0.7854... My result winds up being 0 or NaN

I need some insight again. I am trying to multiply three inputs times two hidden numbers. Two inputs being the same number (since i have yet to figure out how to Square a input). The calculation i am after is a Force calc we use in O&G. Wire diameter * Wire Diameter * Well Head Pressure * .7854(variable) * 1.5;; Eg. .125 * .125 * 6500 * .7854 * 1.5; Which should result in 119.65 (lbs)- instead i get NAN or if i use decimal like this 0.125 i get a result of 0. To Note the function works if i leave the decimal out all together but the answer is wrong naturally.
My Code
<div class="containerForce">
<p>
<h1>Force Calculation - Weight Required to Fall</h1>
<label>Wire OD</label>
<input type="number" id="num05">
<label>Wire OD</label>
<input type="number" id="num06">
<label>Well Head Pressure</label>
<input type="number" id="num07">
<p>
<input type="button" id="btn01" style="background-color: rgb(104, 199, 206)"
value="Required Weight" onclick="cal()" />
</p>
<p id="total3"></p>
</div>
Java Function
function cal() {
var numZero5 = document.getElementById('num05').value;
var numZero6 = document.getElementById('num06').value;
var numZero7 = document.getElementById('num07').value;
var total3 = parseInt(numZero5) * parseInt(numZero6) * parseInt(numZero7) * .7854 * 1.5;
var p = document.getElementById('total3');
p.innerHTML += total3;
}
Currently you are parsing your inputs to Integers. Integers are whole numbers, so everything after the decimal seperator is thrown away.
You can reproduce this behaviour by executing parseInt(1.5) in the browser console.
The method you are looking for is parseFloat() or Number(). I personally would go with parseFloat().
Additionally, you might want to change your last line to p.innerHTML = total3; so you replace the result in the paragraph instead of concetinating your results.
<div class="containerForce">
<h1>Force Calculation - Weight Required to Fall</h1>
<label>Wire OD</label>
<input type="number" id="num05">
<label>Wire OD</label>
<input type="number" id="num06">
<label>Well Head Pressure</label>
<input type="number" id="num07">
<p>
<input type="button" id="btn01" style="background-color: rgb(104, 199, 206)"
value="Required Weight" onclick="cal()" />
</p>
<p id="total3"></p>
</div>
<script>
function cal() {
var numZero5 = document.getElementById('num05').value;
var numZero6 = document.getElementById('num06').value;
var numZero7 = document.getElementById('num07').value;
var total3 = parseFloat(numZero5) * parseFloat(numZero6) * parseFloat(numZero7) * .7854 * 1.5;
var p = document.getElementById('total3');
p.innerHTML = total3;
}
</script>

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>

Issue with simple calculation script

I'm trying to make a really simple calculator for my website.
Basically, I want people to be able to put in their weight into a text box, click "Calculate Dose" and then the script multiplies their weight by a number that I will set myself for each page.
Here is what I have right now. Not only does it not work, but it also stops one of my ads from displaying:
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()">
<input id="result" />
</div>
<script>
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight.value * 1;
result.value = dosage;
}
</script>
What's wrong with it?
You are missing closing tag /> in your button
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You already stored weight value
var weight = document.getElementById('inputweight').value;
So you dont need this var dosage = weight.value * 1;
So use var dosage = weight * 1;
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
this line:
var weight = document.getElementById('inputweight').value;
and this:
var dosage = weight.value * 1;
do not work together well. You are retrieving the value, then the value of that... which cannot work.
So, replace the second line with:
var dosage = weight * 1;
Besides: You should check the console for errors, it should show up there.
I assume (or, guess, more correctly) that the ad that is no longer working stops because the javascript execution is typically terminated after an error.
Just update this line (remove the value attribute which is already extracted above):
var dosage = * 1;
This will work but you might also want to add this for increased type safety (it parses weight as a number):
var dosage = parseInt(weight, 10) * 1;
In your code block you are missing a closing / at the end of the second input statement. Which should be giving you an issue in your html.
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You also don't need weight.value again in the third line of your function. Instead it should be:
var dosage = weight * 1;
Fiddle demonstrating your example modified to work:
http://jsfiddle.net/x38ommxs/
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()" />
<input id="result" />
</div>
Added missing closing tag on button
Changed dosage to multiply the value stored in weight by one.

from a html form to javascript

I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>
Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;
I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.
Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>
if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}

Categories

Resources