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>
Related
My code is here. Below is the HTML:
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsVoltage()" onchange="EqualsVoltage()"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsCurrent()" onchange="EqualsCurrent()"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsResistance()" onchange="EqualsResistance()"> </p>
<script language="Javascript" type="text/javascript" src="EandM.js"></script>
</body>
</html>
Here is the Javascript:
//Electricity and Magnetism Stuff
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputVoltage").value = (Current * Resistance);
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputResistance").value = (Voltage / Current);
}
I want my calculator to react to both oninput and onchange events when I change a value in the text field.
I've been able to make a converter that converts kilometers to miles when oninput and onchange were functioning; however, I can't figure this out.
When I enter data in the field, it doesn't change the other values. Please help!
The problem: when user edit e.g. voltage in input then calculations at the same time change that input value (the input values and calculated values are usually different). Solution: show output calculations in separate place - not as input values. When you use oninput you don't need to use onchange.
function calc() {
let c = inputCurrent.value;
let r = inputResistance.value;
let v = inputVoltage.value;
msg.innerHTML = `voltage: ${ c*r } <br>`
+ `current: ${ v/r } <br>`
+ `resistance: ${ v/c } <br>`;
}
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="calc()">
</p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="calc()">
</p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="calc()">
</p>
Calculations:
<div id="msg"></div>
This works. Should have been checking the other text boxes not the current one. It will keep changing the fields as the user increases or decreases the value.
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<head>
<script type="text/javascript">
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Resistance != "0" && Current != "0" ){
document.getElementById("inputVoltage").value = (Current * Resistance);
}
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Resistance != "0" ){
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Current != "0" ){
document.getElementById("inputResistance").value = (Voltage / Current);
}
}
</script>
</head>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsResistance(); EqualsCurrent()" value="0"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsVoltage(); EqualsResistance()" value="0"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsCurrent();EqualsVoltage()" value="0"> </p>
</body>
</html>
There is already a great answer you can take, but I wanted to provide you an alternative. It's up to you which one fits better to your needs.
This solution provides an alternative for the user to decide when to calculate the values. This can avoid unexpected values as Infinity, 0, etc..
For this, you could give a button to every element in order to let the user click the one he wants the result for. This will update the value to the input box where he presses the button. The button would look like this:
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance"><!-- Add this to every input -->
Calc
</button>
</p>
And your JavaScript code will look like this:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
I hope this gives you another way to achieve what you want.
Here is a fiddle of what I am talking about:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number">
<button id="calcVoltage">
Calc
</button></p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number">
<button id="calcCurrent">
Calc
</button></p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance">
Calc
</button></p>
I would recommend using onkeyup instead of onchange and oninput. [edit] Wont work with the buttons, however.
I'm guessing the workflow is "When I enter something two number fields, the third one is calculated".
But what happens then if all three text fields are filled in?
If you filled in voltage, current, and resistance, and then change voltage again, should current or resistance change?
You need to think about workflow before you do any coding, and that's why the code is wrong.
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>
I have a very basic form that I want to pass data from another form on it without using php at all. Both forms appear properly but I cannot figure out how to transfer data from the first form to the second one with javascript code.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form action"" method="get" onsubmit="submitForm();" name="submitForm">
Company Name:<input type="text"name="companyName"><br><br>
Owner: <input type="text" name="compOwner"><br><br>
Address: <input type="text" name="address"><br><br>
Phone Number:<input type="text" name="phoneNum"><br><br>
Annual Sales($)<input type="text" name="annualSales"><br><br>
Borrow Amount($)<input type="text" name="borrowAmount"><br><br>
Payment Terms(Months)<input type="text" name="paymentTerms"><br><br>
<input type="submit" value="Submit" onclick="submitForm();">
</form>
<form action"" method="get" name="secondForm">
Name of Borrowing Company<input type="text"id="compName"><br><br>
Annual Sales<input type="text"id="annSales"><br><br>
Borrow Amount<input type="text"id="amountBorrowed"><br><br>
Payment Terms<input type="text"id="payTerms"><br><br>
Total Interest On Loan<input type="text"id="totalInterest"><br><br>
Total Payment<input type="text"id="totalPay"><br><br>
Total Profit <input type="text"enabled="false" id="totalProfit"><br><br>
</form>
<script>
function submitForm()
{
compName = document.forms["submitForm"]["companyName"].value;
annualSales = document.forms["submitForm"]["annualSales"].value;
borrowAmount = document.forms["submitForm"]["borrowAmount"].value;
months = document.forms["submitForm"]["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').setAttribute(value, compName);
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
}
</script>
</body>
</html>
I figured it out. There are several problems with this code actually.
First, name of the first form element clashes with name of your function. That is because when an element has a name attribute, it creates a new variable in JS global scope and rewrites your function, because it has the same name. Your form name attribute must be something else that your function name.
<form action"" method="get" onsubmit="submitForm();" name="submitF">
Next, input type="submit" refreshes the page, which you probably don't want. You could add a button element after the form.
</form>
<button onclick="submitForm()">Submit</button>
In JS, submitF is a variable with your form element (thanks to the name attribute), so you can write it simpler without use of document.forms.
function submitForm() {
compName = submitF["companyName"].value;
annualSales = submitF["annualSales"].value;
borrowAmount = submitF["borrowAmount"].value;
months = submitF["paymentTerms"].value;
(...)
}
Also, setAttribute(value, compName) doesn't work. It just doesn't. Assign to value instead like in the rest of the code.
My whole working code looks like this:
<html>
<head>
<title>HTML Form</title>
<script type="text/javascript">
function submitForm() {
compName = submitF["companyName"].value;
annualSales = submitF["annualSales"].value;
borrowAmount = submitF["borrowAmount"].value;
months = submitF["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').value = compName;
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
}
</script>
</head>
<body>
<form action"" method="get" onsubmit="submitForm();" name="submitF">
Company Name:<input type="text"name="companyName"><br><br>
Owner: <input type="text" name="compOwner"><br><br>
Address: <input type="text" name="address"><br><br>
Phone Number:<input type="text" name="phoneNum"><br><br>
Annual Sales($)<input type="text" name="annualSales"><br><br>
Borrow Amount($)<input type="text" name="borrowAmount"><br><br>
Payment Terms(Months)<input type="text" name="paymentTerms"><br><br>
</form>
<button onclick="submitForm()">Submit</button>
<form action"" method="get" name="secondForm">
Name of Borrowing Company<input type="text"id="compName"><br><br>
Annual Sales<input type="text"id="annSales"><br><br>
Borrow Amount<input type="text"id="amountBorrowed"><br><br>
Payment Terms<input type="text"id="payTerms"><br><br>
Total Interest On Loan<input type="text"id="totalInterest"><br><br>
Total Payment<input type="text"id="totalPay"><br><br>
Total Profit <input type="text"enabled="false" id="totalProfit"><br><br>
</form>
</body>
</html>
That's it. Hope I helped.
EDIT: Also, you should always put your JS code in your <head>, unless you have a very good reason not to.
You might want to change document.getElementById('compName').setAttribute(value, compName);
to
document.getElementById('compName').value = compName;
Also, you should convert your number values from String to an Integer
ex.
annualSales = parseInt(document.forms["submitForm"]["annualSales"].value)
Other than that, the javascript seems fine.
UPDATE:
Upon investigating further. Your submit is occurring before the javascript is run, that is why the fields are not getting populated. I would suggest you put your javascript in an event listener for submit.
document.forms['submitForm'].submit(function() {
compName = document.forms["submitForm"]["companyName"].value;
annualSales = document.forms["submitForm"]["annualSales"].value;
borrowAmount = document.forms["submitForm"]["borrowAmount"].value;
months = document.forms["submitForm"]["paymentTerms"].value;
totalInterest = borrowAmount * (months/12) * 0.03;
totalPayment = borrowAmount + totalInterest;
profit = totalPayment - borrowAmount;
document.getElementById('compName').setAttribute(value, compName);
document.getElementById('annSales').value = annualSales;
document.getElementById('amountBorrowed').value = borrowAmount;
document.getElementById('payTerms').value = months;
document.getElementById('totalInterest').value = totalInterest;
document.getElementById('totalPay').value = totalPayment;
document.getElementById('totalProfit').value = profit;
});
NOTE: Your page will refresh when you do a submit, and you won't see the values be populated.
I have studied java and php for many years and recently just started developing in JavaScript as well. Anyway a fairly noob question but can anyone work out why this application isn't showing displaying the interest when the button is clicked? I have been using w3schools website to learn from.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Interest Calculator</title>
</head>
<body>
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
</body>
</html>
Many thanks,
Adam
You need to explicitly specify *. It is not normal for 5(3) = 15 in JavaScript or any programming language. You need to explicitly specify 5*(3):
var sum = amount*(1+rate)^years;
Working Code
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount*(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
Fiddle: http://jsbin.com/lovevazaxe
The OP uses the ^ operator and presumably wants to use the power-of operator.
In javascript the ^ operator refers to bitwise XOR - I don't think that's what the OP wants.
Instead, the power-of operation is done with the Math.pow() function.
So replace var sum = amount(1+rate)^years; with
var sum = Math.pow(amount*(1+rate),years)
I am doing a java script application that calculates Miles driven / gallons used and gallons used* price per gallon. I have two problems:
1) when I enter all the values price per gallon adds a another zero automatically. For example 40, becomes 400.
2) I am looking to write the result of both calculations underneath the button.
If anyone can give me guidance or help I would really appreciate it.
<!DOCTYPE
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
}
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value); //alert(miles);
var gallons = parseFloat($("gallons").value);
var costGallon = document.getElementById("costGallon").value;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
}
else {
var mpg = miles/gallons;
var costGallon = gallons*costGallon;
$("costGallon").value=costGallon.toFixed(2);
//alert("your total is" +mpg );
alert("your total new is " + costGallon);
//cost of trip = gallons used * price per gallon
}
}
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
}
</script>
</head>
<section>
<body>
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br><br>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br><br>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br><br>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span>
</section>
</body>
</html>
Can you give me an example of where it does that? I copy pasted your code and for me it gives the correct values. From what I understand the only thing you are writting into the cost per gallon field is the gallons used times the price per gallon. An that seems to be working fine.
If you can provide me with a example calculation you want to achive i'd be happy to help.
On another note, i suggest not using the same variable again in line 27 that you used to hold the DOM object of the input field. Also toFixed does not change the variable you used it on but return a new variable so instead remove that in line 28 and have line 27 look something like this:
var newVarNameIsBoss = (gallons*costGallon).toFixed(2);
Hope this helps
revised code
<!DOCTYPE html> <!-- scorrect doctype-->
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
};//remember that a var decleration always ends with a ; even if it's a function
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value), //alert(miles);
gallons = parseFloat($("gallons").value),
costGallon = document.getElementById("costGallon").value,
mpg,totalCost;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
} else {
mpg = miles/gallons;
totalCost = (gallons*costGallon).toFixed(2);
costGallon.value=totalCost;
alert("your total new is " + totalCost);
$('totalMpg').innerHTML = String(mpg.toFixed(2)) + " Miles per Gallon";
}
};//remember that a var decleration always ends with a ; even if it's a function
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
};//remember that a var decleration always ends with a ; even if it's a function
</script>
</head>
<body>
<section> <!-- section bellow the body tag-->
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br/><br/>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br/><br/>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br/><br/>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span></p><!--closing p tag here-->
</section>
</body>
</html>