How to make a complex formula working with keyup event - javascript

I am still new in coding. I have to make this formula working.
GPro = 31 * ((Cr / 8.4)-1.5) * (kA-0.2) * kG
It is an online calculator that must work automatically after input from the user (keyup event).
There are three formulas on the site - CrumPro, CrumPo and Gpro (see Codes below). First two are working just fine. However as soon as I add the third one (GPro) in the Script the other two just crashed and stop working. I do something wrong, but I can't understand what. Maybe I use wrong the Math.pow function... I need an expert advise... Or maybe a better code. As I said - the first two formulas worked fine as long the third one is not in the script.
Thanks in advance
Here are the codes:
// Get CrumPro
function getCrPro() {
var CrmgPro= parseFloat($('#demo3').val());
var CrumPro = CrmgPro / 0.05;
var CrPro = CrumPro.toFixed(2);
if (isNaN(CrPro)) CrPro = 0;
$('#demo5').val((CrPro));
}
$(document).ready(function() {
$('#demo3').keyup(function(event) {
getCrPro();
});
});
// Get CrumPo
function getCrPo() {
var CrmgPo = parseFloat($("#res1").val());
var CrumPo = CrmgPo / 0.05;
var CrPo = CrumPo.toFixed(2);
if (isNaN(CrPo)) CrPo = 0;
$('#res2').val((CrPo));
}
$(document).ready(function() {
$('#res1').keyup(function(event) {
getCrPo();
});
});
//get GPro
function getGPro () {
var Cr = parseFloat($("#demo3").val());
var Cru = Cr / 0.05;
var Cru2 = Cru.toFixed(2);
var Cr8 = Cru2 / 8.4;
var kCr = Math.pow (Cr8, -1,5);
var kA = parseFloat($("#demo1").val());
var kAP = Math.pow (kA, -0,2);
var kG = parseFloat($("#demo4").val());
var G = (31 * kCr * kAP * kG);
if (isNaN(G)) G = 0;
$('#demo6').val((G));
}
$(document).ready(function() {
$('#demo3').keyup(function(event) {
getGPro();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="demo1" type=“number” name="age" placeholder="age">
<label for="demo1">kA (age)</label>
<br />
<input id="demo2a" class="gender" type="radio" name="gender" value="0,742" onClick="document.getElementById('demo4').value=this.value">
<label for="demo2a">female</label>
<input type="radio" name="gender" id="demo2b" class="gender" value="1" onClick="document.getElementById('demo4').value=this.value">
<label for="demo2b">male</label>
<br />
<input id="demo4" type="text" name="kG" placeholder="kG" readonly="true" value="0">
<label for="demo4">kG</label>
<br />
<input id="demo3" type="number" name="Cr" placeholder="CrPro">
<label for="demo3">CrPro</label>
<br />
<input id="demo5" type="text" name="CrumPro" readonly="true" placeholder="=CrPro/0,01131222" value="0">
<label for="demo5"> CrumPro </label>
<br />
<input id="demo6" type="text" name="GPro" readonly="true" placeholder=" GPro = 31 * ((Cr / 8.4)^-1.5) * (kA^-0.2) * kG)">
<label for="demo6"> GPro </label>
<br />
<input id="res1" type="number" name="CrPo" placeholder="Crea (mg/dL)">
<label for="res1"> CrPo </label>
<br />
<input id="res2" type="text" name="CrumPo" readonly="true" value="0" placeholder="= CrPo/0.01131222">
<label for="res2">CrumPo</label>
<br />
<input id="res3" type="text" name="GPo" readonly="true" placeholder="GPo = 31 * ((Cr / 8.4)^-1.5) * (kA^-0.2) * kG)">
<label for="res3">GPo</label>

Just a typo; you missed semicolon in getGPro code:
var G = (31 * kCr * kAP * kG)
Must be:
var G = (31 * kCr * kAP * kG);
UPDATE:
Also the getGPro function definition has a typo. function must be in lowercase:
function getGPro ()

You're using var with a capital V in your getGPro function

Related

Javascript: Real time calculations in a form

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

i want to display addition of textbox id=ttlpw and id=tplpw in id=twork.but its not working

i want to add the first and second function value in third function.and i am using this third function value to display on one textbox.
i have tried to directly add the function and get the result but it doesnt work
i tried different function like onkeydown, onkeypress etc.
//first function
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value)
var tl = parseInt(document.getElementById("tlpw").value)
document.getElementById("ttlpw").value = tt * pp * tl;
}
//second function
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
document.getElementById("tplpw").value = tt * pp * tl;
}
//third function
function third() {
X = first();
Y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" " onkeyup="third() "
class="form-control " />
<input type="text " id="tplpw " name="tplpw "" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
This code does not give the addition of the value. I am expecting addition of x+y.
There are several issues:
Your functions first() and second() print the value, but they don't actually return those values.
On top of that, you have superfluous/random " characters and space characters which cause your inputs to not behave as expected.
Finally, you assign X and Y and then try to add x and y, but Javascript is case sensitive so the addition tries to add two undefined values.
In the below snippet (click Show to see it) I fixed all of that, and I added placeholders so at least we have some indication of what we are typing into.
As a last note, it looks like cname and nseb are not being used anywhere, also they do not have a keyup event like most of the others.
It still looks a bit messy to me; I hope it makes more sense to you.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" class="form-control " />
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
Update:
If I understand your need correctly, instead of doing onkeyup="first()" and onkeyup="second()", try changing them all to use onkeyup="third()". third() will call both the other functions, each of which will show their outcome, and then third() will show the sum of both.
Here is a new snippet that will do that. I also removed cname and nseb, and rearranged the order of inputs so they actually make sense.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
div { width: 240px; text-align: right; }
input { width: 40px; }
<div>
<input type="text" id="npt" name="npt" onkeyup="third()" /> *
<input type="text" id="divi" name="divi" onkeyup="third()" /> *
<input type="text" id="tlpw" name="tlpw" onkeyup="third()" /> =
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" /><br />
<input type="text" id="npp" name="npp" onkeyup="third()" /> *
<input type="text" id="nob" name="nob" onkeyup="third()" /> *
<input type="text" id="plpw" name="plpw" onkeyup="third()" /> =
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" /><br />
<input type="text" id="twork" name="twork" /><br />
</div>
You need that functions first and second to return the value:
function first () {
...
return tt * pp * tl
}

Superscript Calculation Javascript Variables

I'm exercising in calculations with variables using javascript and i can't figure out how to use superscripts in variables. With some help Javascript calculations holding variables i learned how to do calculations in general but my new question is how to use superscripts?
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis*/ + 0.00000055 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis and ^2 outside the parenthesis*/ - 0.00028826;
}
</script>
Thanks in advance
There is a function in javascript Math.pow();
Math.pow(2,4) gives you 2^4 = 16.
Math.pow(2,4);
>16
Math.pow(2,4.1);
>17.148375400580687
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
}
</script>
Updated Snippet according to answers works now!

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

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

Javascript Update Total Sum from Fields

I have created the code using Javascript but I'm getting and error when I hit the calculate button.
the formula im using is this:
A + B + C + D x E% + F =
The error I'm receiving is:
{"error": "Please use POST request"}
The code im using is:
// define a function to perform our calculation.
function calculate() {
// retrieve the values from the amount and percentage fields
// and store them in variables.
var A = $('#A').val();
var B = $('#B').val();
var C = $('#C').val();
var D = $('#D').val();
var E = $('#E').val();
var F = $('#F').val();
// calculation
var total = A + B + C + D * (E / 100) + F;
$('#total').val(total.toFixed(2));
return false;
}
$('#calculator').submit(calculate);
<form id="calculator">
<p>Base:
<input id="A" value="0.00" />
</p>
<p>Rush:
<input id="B" value="0.00" />
</p>
<p>Added:
<input id="C" value="0.00" />
</p>
<p>Extra:
<input id="D" value="0.00" />
</p>
<p>Ship:
<input type ="hidden" id="E" value="5" />
</p>
<p>
<input id="F" value="0.00" />
</p>
<hr />
<p>Total:
<input id="total" disabled="disabled" />
</p>
<p>
<input type="submit" />
</p>
</form>
I have create a plugin to create calculation form called calx, you can download it here
just define data formula in the target element, and initialize calx
<form id="calculator">
<p>Base: <input type="text" id="A" value="0.00" /></p>
<p>Rush: <input type="text" id="B" value="0.00" /></p>
<p>Added: <input type="text" id="C" value="0.00" /></p>
<p>Extra: <input type="text" id="D" value="0.00" /></p>
<p>Ship: <input type ="hidden" id="E" value="5" /></p>
<p><input type="text" id="F" value="0.00" /></p>
<hr />
<p>Total: <input type="text" id="total" disabled="disabled" data-formula="$A + $B + $C + $D * ($E/100) + $F" /></p>
<p><input type="submit" id="calculate" /></p>
</form>
javascript section
$(document).ready(function(){
$('#calculator').calx({autocalculate:false});
$('#calculate').click(function(e){
e.preventDefault();
$('#calculator').calx('update');
});
});
You're getting an unhandled TypeError from the middle of calculate():
$('#total').val(total.toFixed(2));
// TypeError: Object 0.000.000.0000.00 has no method 'toFixed'
With it being thrown, return false; isn't evaluated and the <form> still submits as normal. And, {"error": "Please use POST request"} is JSFiddle's way of refusing to handle the request since it's sent with HTTP GET.
The error is because total, A, B, etc. aren't Numbers and + also concatenates:
var total = A + B + C + D * (E / 100) + F;
// total = "0.00" + "0.00" + ... + "0.00";
<input> values are always Strings, so you'll need to parse them in order to add Numbers rather than concat Strings:
var A = parseFloat($('#A').val());
var B = parseFloat($('#B').val());
var C = parseFloat($('#C').val());
var D = parseFloat($('#D').val());
var E = parseFloat($('#E').val());
var F = parseFloat($('#F').val());
http://jsfiddle.net/wKr3u/
And, while the differences are negligible in most cases, e.preventDefault() (as Jeff Mercado suggested) has one benefit over return false:
It can be used sooner in the event handler, allowing the default action to still be prevented despite an error.
function calculate(ev) {
ev.preventDefault();
// retrieve the values from the amount and percentage fields
// ...
}
assuming that you want it to just calculate the total without actually submitting, you need to stop the submit event from proceeding:
$('#calculator').on('submit', function(ev) {
ev.preventDefault();
calculate();
});
On your code total.toFixed(2) giving this error and by default javascript will take the value as string so You have to handle that to
Update
string to number just do like this
var total = A*1 + B*1 + C*1 + D * (E / 100) + F*1;
HERE IS THE SOLUTION

Categories

Resources