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

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>

Related

Html form input to variable for use in a js function

<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
</label>
<input type="submit" value="submit"/>
</form>
script trying to take that input into a variable for a function to
return that inpunt and * to print in web
<script language="javascript">
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
return (Honorarios, Escribania, sellos);
console.log(gasto);
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
alert(gasto, Honorarios, Escribania, sellos);
}
calculos();
</script>
sorry if i dont explain good enough im learing html and js and wanted to make a calculator that you input a amount and the algorithm gives you back that amount * by 0.05 and others thanks
I edited your code, and removed the unnecessary lines, also moved the label HTML element which was badly placed, it works now, watch out for console log.
I also combined all results into a single string before alert line.
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
let allOfThem = `Honorarios: ${Honorarios}
Escribania: ${Escribania}
sellos: ${sellos}`
alert(allOfThem);
}
//calculos(); This function SHOULD never be here, as it will be called everytime.
<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
</label> <!-- This was moved here to the right place, it was at the end of form -->
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
<input type="submit" value="submit"/>
</form>

javascript calculator works only after refreshing the page

I made this calculator http://fernandor80.neocities.org/plancalc/tomx2.html
and it always returns Nan, but once you reload it (with the previously entered inputs), it works...
I've been looking around but I can not figure it out... So I'm here because I really want to get it to work.
here is the code to it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plant Calc V1.2</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins<h2 id="bin45"></h2>
90 count bins<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
<script language="JavaScript">
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr/bed ;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp/45 ;
var bin90 = totalp/90 ;
var nowp = document.getElementById("nowp").value;
var nowb = nowp/ppb ;
function row(){
document.getElementById("ppb").innerHTML = ppb;
}
function total(){
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now(){
document.getElementById("nowb").innerHTML = nowb;
}
</script>
</body>
</html>
Also it doesnt work on mobile devices..I made a pure javascript prompt based calculator for that, but for the purpose of learning i would like some pointers.
I really feel bad about asking a question thats been answered hundreds of times. Sorry, I just had to..
the values of ppr, bed, and ppb are calculated when the page first loads. Thus it's a NaN.
You should consider move at least the data retrieval and calculation inside function row().
One simple way to debug issue like this, if you don't use any IDE, it to press f12 in your browser and open dev mode where you can set break point and check the current value of your variables.
You have dependency over other variable in every function. Instead of using global variables, you can access value in each function.
function row() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
document.getElementById("ppb").innerHTML = ppb;
}
function total() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
var nowp = document.getElementById("nowp").value;
var nowb = nowp / ppb;
document.getElementById("nowb").innerHTML = nowb;
}
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins
<h2 id="bin45"></h2>
90 count bins
<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
It will always NaN because your call values of ppr, bed, and ppb when just first page loaded ! At that page loaded time ,you didn't have any value so NaN getting.So when you click ,you should call that value again ,make it function to call values will be more better...
here I push init() to get value onclick
<script type="text/javascript">
var ppr,bed,ppb,totalp,totalb,bin45,bin90,nowb,nowb;
function init(){
ppr = parseFloat(document.getElementById("ppr").value);
bed = parseFloat(document.getElementById("bed").value);
ppb = ppr/bed ;
totalb = parseFloat(document.getElementById("totalb").value);
totalp = totalb * ppb;
bin45 = totalp/45 ;
bin90 = totalp/90 ;
nowp = document.getElementById("nowp").value;
nowb = nowp/ppb ;
}
function row(){
init();
document.getElementById("ppb").innerHTML = ppb;
}
</script>

Javascript variable displaying NaN

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)

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

Want to output a visual price

ok, I've spent the past 5 hours trying to codge together a small javascript code for a website.
Basically the widths are set values of 2 or 4 (which the user will use a simple drop-down option).
Length can be anything from 1 to 60.
The price will be a fixed price, so can just be hidden out of the way.
Now this is where I start to go South with the situation, I'm having problems spitting the result out into a div area on the page, this is what I have so far;
<script type="text/javascript">
function only_numbers(value){
var check_this = value;
var expression = /^\d*\.*\d*$/;
if(expression.test(check_this)){ return true; }
else{ return false; }
}
function calculate(){
var lengthVal = document.mult.lengthVal.value;
var heightVal = document.mult.heightVal.value;
var priceVal = document.mult.priceVal.value
var showValue = 0;
if(only_numbers(lengthVal) && only_numbers(heightVal) && only_numbers(priceVal)){
var showValue = ((lengthVal * heightVal) * 1.25) * priceVal;
// showValue = Math.round(showValue * 100) / 100;
document.getElementById('showValue').innerHTML = "showValue";
}else{
alert("Please enter only numerical values.");
}
}
</script>
</head>
<body>
<form name="mult">
Length: <input type="text" name="lengthVal" /> <br />
Height: <input type="text" name="heightVal" /> <br />
Price: <input type="text" name="priceVal" /> <br />
<input type="button" value="Calculate" onClick="calculate()" />
</form>
<div id="showValue"></div>
I know I've not sorted the price out to be hidden and is just an open variable atm, please guys, any help would be great.
document.getElementById('showValue').innerHTML = "showValue";
You probably want to write your variable value in there, not the string "showValue". So you should be using:
document.getElementById('showValue').innerHTML = showValue;

Categories

Resources