Calculation in JQuery gives result "NaN" - javascript

Trying to do some calculations using jquery:
Run the below snippet: put values
Quantity as 1
Buy as 111
Sell as 111.22
The result will be NaN.
Why this is happening? How to resolve this issue?
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#quantity, #buy, #sell").on("change keyup paste", function() {
var quantity = Number($('#quantity').val());
var buy = Number($("#buy").val());
var sell = Number($("#sell").val());
var total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
if (brokerage_amnt_buy >= 25) {
var brokerage_buy = 25;
} else {
var brokerage_buy = brokerage_amnt_buy;
}
var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
if (brokerage_amnt_sell >= 25) {
var brokerage_sell = 25;
} else {
var brokerage_sell = brokerage_amnt_sell;
}
var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST
var total_charges = roundToTwo(brokerage + transaction_charges + gst);
var pnl = roundToTwo(((sell - buy) * quantity) - total_charges);
$('#pnl_display').text(pnl);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table table-borderless">
<tbody>
<tr style="text-align: center;">
<td><b>Quantity</b></td>
<td><b>Buy</b></td>
<td><b>Sell</b></td>
</tr>
<tr>
<td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
<td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
<td><input type="number" class="form-control" id="sell" placeholder="Sell Amount" name="sell"></td>
</tr>
<tr id="pnl_color">
<td><span id="pnl_text_display">Profit / Loss</span></td>
<td><span id="pnl_display"></span></td>
</tr>
</tbody>
</table>
Run the above snippet: put values
Quantity as 1
Buy as 111
Sell as 111.22
The result will be NaN.
Why this is happening? How to resolve this issue?

instead of roundToTwo you can use .tofixed(2) then problem resolves. Because your answer return with e (-1.1379786002407855e-15) so it shows NaN.
var pnl = parseFloat(((sell - buy) * quantity) - total_charges).toFixed(2);
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#quantity, #buy, #sell").on("change keyup paste", function() {
var quantity = Number($('#quantity').val());
var buy = Number($("#buy").val());
var sell = Number($("#sell").val());
var total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
if (brokerage_amnt_buy >= 25) {
var brokerage_buy = 25;
} else {
var brokerage_buy = brokerage_amnt_buy;
}
var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
if (brokerage_amnt_sell >= 25) {
var brokerage_sell = 25;
} else {
var brokerage_sell = brokerage_amnt_sell;
}
var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST
var total_charges = roundToTwo(brokerage + transaction_charges + gst);
var pnl = parseFloat(((sell - buy) * quantity) - total_charges).toFixed(5);
pnl = roundToTwo(pnl);
$('#pnl_display').text(pnl);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table table-borderless">
<tbody>
<tr style="text-align: center;">
<td><b>Quantity</b></td>
<td><b>Buy</b></td>
<td><b>Sell</b></td>
</tr>
<tr>
<td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
<td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
<td><input type="number" class="form-control" id="sell" placeholder="Sell Amount" name="sell"></td>
</tr>
<tr id="pnl_color">
<td><span id="pnl_text_display">Profit / Loss</span></td>
<td><span id="pnl_display"></span></td>
</tr>
</tbody>
</table>

I modified yout roundToTwo() function to handle precision errors:
function roundToTwo(num) {
return parseFloat(num.toFixed(2));
}
$("#quantity, #buy, #sell").on("change keyup paste", function() {
var quantity = Number($('#quantity').val());
var buy = Number($("#buy").val());
var sell = Number($("#sell").val());
var total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
if (brokerage_amnt_buy >= 25) {
var brokerage_buy = 25;
} else {
var brokerage_buy = brokerage_amnt_buy;
}
var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
if (brokerage_amnt_sell >= 25) {
var brokerage_sell = 25;
} else {
var brokerage_sell = brokerage_amnt_sell;
}
var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST
var total_charges = roundToTwo(brokerage + transaction_charges + gst);
var pnl = roundToTwo(((sell - buy) * quantity) - total_charges);
$('#pnl_display').text(pnl);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table table-borderless">
<tbody>
<tr style="text-align: center;">
<td><b>Quantity</b></td>
<td><b>Buy</b></td>
<td><b>Sell</b></td>
</tr>
<tr>
<td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
<td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
<td><input type="number" class="form-control" id="sell" placeholder="Sell Amount" name="sell"></td>
</tr>
<tr id="pnl_color">
<td><span id="pnl_text_display">Profit / Loss</span></td>
<td><span id="pnl_display"></span></td>
</tr>
</tbody>
</table>

#Orever can you try again after replacing the line ( return +(Math.round(num + "e+2") + "e-2"); ) with ( return +(Math.round(num * 100) / 100); ) in the function roundToTwo(num).
So your code will be
function roundToTwo(num) {
return +(Math.round(num * 100) / 100);
}

Related

How do I use an input to define decimals for other inputs?

I am trying to set the number of decimals of many inputs by using a specific input.
Here is what I am doing:
window.oninput = function(event) {
var campo = event.target.id;
// DECIMALS
if (campo == "decimalTemp") {
var i = decimalTemp.value;
ºC.value.toFixed = i;
ºK.value.toFixed = i;
ºF.value.toFixed = i;
ºRa.value.toFixed = i;
}
// TEMPERATURE
if (campo == "ºC") {
ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
} else if (campo == "ºK") {
ºC.value = (ºK.value * 1 - 273.15).toFixed(2);
ºF.value = (ºK.value * 1.8 - 459.889).toFixed(2);
ºRa.value = (ºK.value * 1.8).toFixed(2);
} else if (campo == "ºF") {
ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(2);
ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(2);
ºRa.value = (ºF.value * 1 + 459.67).toFixed(2);
} else if (campo == "ºRa") {
ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(2);
ºK.value = (ºRa.value / 1.8).toFixed(2);
ºF.value = (ºRa.value * 1 - 459.67).toFixed(2);
}
};
<h3>Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> <small>Decimals<small></h3>
Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">
<br> Kelvin (K) <input id="ºK" type="number" min="0" value="293">
<br> Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">
<br> Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">
In summary, I would like to know if this construction is correct:
var i = decimalTemp.value;
ºC.value.toFixed = i;
I already tried something like:
ºC.value.toFixed(i);
But didn't work. Any idea where am I wrong?

Can't figure out what's wrong in my Javascript code

Can't figure out why my Javascript code won't run to show a letter grade and change the background color. I'm new at this, but thought I had it right...any ideas?
Writes the numeric grade in the bottom left cell of the table.
And the associated letter grade in the bottom right cell of the table.
(For this problem use: A >= 90 > B >= 80 > C >= 70 > D >= 60 > F)
If the grade is passing the background color of the letter grade cell changes to green. If the grade is failing the background color of the letter grade cell should turn red.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lab11aKL.html</title>
<meta charset="utf-8">
<style>
</style>
<script>
function addNumbers() {
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
var t3 = document.getElementById("t3");
var t4 = document.getElementById("t4");
var t5 = document.getElementById("t5");
var t6 = document.getElementById("t6");
answer.value = parseFloat(t1.value * .20) + parseFloat(t2.value * .20) +
parseFloat(t3.value * .30) + parseFloat(t4.value * .125) +
parseFloat(t5.value * .125) + parseFloat(t6.value * .05);
}
function gradeLetter() {
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
var t3 = document.getElementById("t3");
var t4 = document.getElementById("t4");
var t5 = document.getElementById("t5");
var t6 = document.getElementById("t6");
var ct1 = parseFloat(t1.value * .20);
var ct2 = parseFloat(t2.value * .20);
var ct3 = parseFloat(t3.value * .30)
var ct4 = parseFloat(t4.value * .125);
var ct5 = parseFloat(t4.value * .125);
var ct6 = parseFloat(t6.value * .05);
if (answer >= 90 > ) {
answergrade = 'A';
document.getElementById("answergrade").style.backgroundColor =
'green';
} else if (answer >= 80 > ) {
answergrade = 'B';
document.getElementById("answergrade").style.backgroundColor =
'green';
} else if (answer >= 70 > ) {
answergrade = 'C';
document.getElementById("answergrade").style.backgroundColor =
'green';
} else if (answer >= 60 > ) {
answergrade = 'D';
document.getElementById("answergrade").style.backgroundColor =
'green';
} else(answer < 60) {
answergrade = 'F';
document.getElementById("answergrade").style.backgroundColor =
'red';
}
}
</script>
</head>
<body>
<form name="tform" id="tform">
<table>
<tr>
<th></th>
<th>Score</th>
</tr>
<tr>
<td>Test 1</td>
<td><input type="text" name="t1" id="t1" /></td>
</tr>
<tr>
<td>Test 2</td>
<td><input type="text" name="t2" id="t2" /></td>
</tr>
<td>Final Exam</td>
<td><input type="text" name="t3" id="t3" /></td>
</tr>
<td>Labs</td>
<td><input type="text" name="t4" id="t4" /></td>
</tr>
<td>Project</td>
<td><input type="text" name="t5" id="t5" /></td>
</tr>
<td>Quizzes</td>
<td><input type="text" name="t6" id="t6" /></td>
</tr>
<tr>
<th colspan="2">
<input type="button" name="b1" id="b1" value="Calculate Grade" onclick="addNumbers(); gradeLetter()" />
</th>
</tr>
<tr>
<td><input type="text" name="answer" id="answer" /></td>
<td><input type="text" name="answergrade" id="answergrade" /></td>
</tr>
</table>
</form>
</body>
</html>
Your issue is missing values. Take a look at if/else clauses
else if (answer >=70 >{??})
There is no x>a>y type of comparison in javascript.
There are several problems here.
You don't have a variable defined for answer that you're referring to in the addNumbers() function.
You are setting answer.value in addNumbers(), but then comparing to answer in all of your conditionals in the gradeLetter() function.
t1 through t6 don't have a value in HTML.
answergrade being calculated in gradeLetter() isn't being written to that HTML element
Your conditionals aren't defined correctly
You can't have else (condition){//condition is true execute this stuff} , it's just else{//execute this code automatically}. When there's a condition after the first if statement use else if (condition){//condition is true execute this stuff}
Please see the below code which should get you pointed in the right direction.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lab11aKL.html</title>
<meta charset="utf-8">
<style>
</style>
<script>
var answer;
function addNumbers()
{
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
var t3 = document.getElementById("t3");
var t4 = document.getElementById("t4");
var t5 = document.getElementById("t5");
var t6 = document.getElementById("t6");
answer = parseFloat(t1.value * .20) + parseFloat(t2.value * .20) +
parseFloat(t3.value * .30) + parseFloat(t4.value * .125) +
parseFloat(t5.value * .125) + parseFloat(t6.value * .05);
}
function gradeLetter()
{
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
var t3 = document.getElementById("t3");
var t4 = document.getElementById("t4");
var t5 = document.getElementById("t5");
var t6 = document.getElementById("t6");
var ct1 = parseFloat(t1.value * .20);
var ct2 = parseFloat(t2.value * .20);
var ct3 = parseFloat(t3.value * .30)
var ct4 = parseFloat(t4.value * .125);
var ct5 = parseFloat(t4.value * .125);
var ct6 = parseFloat(t6.value * .05);
if (answer >=90)
{
answergrade = 'A';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
else if (answer >=80)
{
answergrade = 'B';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
else if (answer >=70)
{
answergrade = 'C';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
else if (answer >=60)
{
answergrade = 'D';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
else if (answer <60)
{
answergrade = 'F';
document.getElementById ("answergrade").style.backgroundColor =
'red';
}
var answerElem = document.getElementById('answergrade')
answerElem.innerText = answergrade;
}
</script>
</head>
<body>
<form name="tform" id="tform">
<table>
<tr>
<th></th>
<th>Score</th>
</tr>
<tr>
<td>Test 1</td>
<td><input type="text" name="t1" id="t1"/>10</td>
</tr>
<tr>
<td>Test 2</td>
<td><input type="text" name="t2" id="t2"/>50</td>
</tr>
<td>Final Exam</td>
<td><input type="text" name="t3" id="t3"/>100</td>
</tr>
<td>Labs</td>
<td><input type="text" name="t4" id="t4"/>90</td>
</tr>
<td>Project</td>
<td><input type="text" name="t5" id="t5"/>70</td>
</tr>
<td>Quizzes</td>
<td><input type="text" name="t6" id="t6"/>85</td>
</tr>
<tr>
<th colspan="2">
<input type="button" name="b1" id="b1"
value="Calculate Grade"
onclick="addNumbers(); gradeLetter()"/>
</th>
</tr>
<tr>
<td><input type="text" name="answer" id="answer"/></td>
<td><input type="text" name="answergrade" id="answergrade"/></td>
</tr>
</table>
</form>
</body>
</html>
There are several problems. Some of them are clearly visible if you use a browser's developer console to troubleshoot. If you are going to program javascript, it's a must to learn how to use the console.
Below is a working snippet. Run it to see it work.
I commented in the code below the variety of problems (just before the fixed code).
function addNumbers() {
var t1 = document.getElementById( "t1" );
var t2 = document.getElementById( "t2" );
var t3 = document.getElementById( "t3" );
var t4 = document.getElementById( "t4" );
var t5 = document.getElementById( "t5" );
var t6 = document.getElementById( "t6" );
var answer = document.getElementById('answer');
answer.value = parseFloat( t1.value * .20 ) + parseFloat( t2.value * .20 ) +
parseFloat( t3.value * .30 ) + parseFloat( t4.value * .125 ) +
parseFloat( t5.value * .125 ) + parseFloat( t6.value * .05 );
}
function gradeLetter() {
// you weren't getting the value for "answer"
// the + casts this to a number, so the comparisons work properly
var answer = +document.getElementById('answer').value;
var t1 = document.getElementById( "t1" );
var t2 = document.getElementById( "t2" );
var t3 = document.getElementById( "t3" );
var t4 = document.getElementById( "t4" );
var t5 = document.getElementById( "t5" );
var t6 = document.getElementById( "t6" );
var ct1 = parseFloat( t1.value * .20 );
var ct2 = parseFloat( t2.value * .20 );
var ct3 = parseFloat( t3.value * .30 )
var ct4 = parseFloat( t4.value * .125 );
var ct5 = parseFloat( t4.value * .125 );
var ct6 = parseFloat( t6.value * .05 );
// This is incorrect and causes a syntax error
// if ( answer >= 90 > ) {
if ( answer >= 90 ) {
answergrade = 'A';
document.getElementById( "answergrade" ).style.backgroundColor =
'green';
}
else if ( answer >= 80 ) {
answergrade = 'B';
document.getElementById( "answergrade" ).style.backgroundColor =
'green';
}
else if ( answer >= 70 ) {
answergrade = 'C';
document.getElementById( "answergrade" ).style.backgroundColor =
'green';
}
else if ( answer >= 60 ) {
answergrade = 'D';
document.getElementById( "answergrade" ).style.backgroundColor =
'green';
}
else if (answer < 60)
{
answergrade = 'F';
document.getElementById( "answergrade" ).style.backgroundColor =
'red';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lab11aKL.html</title>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<form name="tform" id="tform">
<table>
<tr>
<th></th>
<th>Score</th>
</tr>
<tr>
<td>Test 1</td>
<td><input type="text" name="t1" id="t1"/></td>
</tr>
<tr>
<td>Test 2</td>
<td><input type="text" name="t2" id="t2"/></td>
</tr>
<td>Final Exam</td>
<td><input type="text" name="t3" id="t3"/></td>
</tr>
<td>Labs</td>
<td><input type="text" name="t4" id="t4"/></td>
</tr>
<td>Project</td>
<td><input type="text" name="t5" id="t5"/></td>
</tr>
<td>Quizzes</td>
<td><input type="text" name="t6" id="t6"/></td>
</tr>
<tr>
<th colspan="2">
<input type="button" name="b1" id="b1"
value="Calculate Grade"
onclick="addNumbers(); gradeLetter()"/>
</th>
</tr>
<tr>
<td><input type="text" name="answer" id="answer"/></td>
<td><input type="text" name="answergrade" id="answergrade"/></td>
</tr>
</table>
</form>
</body>
</html>
Close out you if and if else conditions:
if (answer >=90 >){
answergrade = 'A';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
Should be
if (answer >=90){
answergrade = 'A';
document.getElementById ("answergrade").style.backgroundColor = `
'green';
}
And the if else conditions need to be closed as well
if (answer >=80){
answergrade = 'B';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}
Should be
if (answer >=80 && answer < 90){
answergrade = 'B';
document.getElementById ("answergrade").style.backgroundColor =
'green';
}

percentages when converting sterling to euro

Hi I am trying to convert Sterling to Euros. But I can't seem to get the percentages correct. I have tried it several ways without luck. The idea is to get 1% of the sterling price then multiply it by the conversion rate and add it to the sterling price to make the euro total, and then do the same with vat.
Hope someone can help, thanks!
Here is my code.
var input = document.querySelectorAll('input');
var conversionRate = input[0];
var sterling = input[1];
var vat = input[2];
var euro = input[3];
init();
function init() {
calculateKeyUp();
}
function calculateKeyUp() {
for (var i = 0; i < input.length; i++) {
input[i].addEventListener("keyup", function() {
//var totalLessVat = (sterling.value) + (conversionRate.value * (sterling.value / 100));
var sterling1Per = sterling.value / 100;
var convert = sterling1Per * conversionRate.value;
var totalLessVat = convert + sterling.value;
//var total = (totalLessVat) + (vat.value * (totalLessVat / 100));
var euro1Per = totalLessVat / 100;
var addVat = euro1Per * vat.value;
var total = addVat + totalLessVat;
euro.value = Math.floor(total);
});
}
}
<div id="calculator-form">
<table>
<tr>
<td>Conversion Rate: </td>
<td><input type="number" id="conversionRate"> %</td>
</tr>
<tr>
<td>Sterling Price: </td>
<td><input type="number" id="sterling"> £</td>
</tr>
<tr>
<td>Vat: </td>
<td><input type="number" id="vat"> %</td>
</tr>
<tr>
<td>Euro Price is </td>
<td><input type="number" id="euro" disabled> €</td>
</tr>
</table>
</div>
The .value of an input is going to be a String, so you will need to parse the number out of each input you are working with. If it's an int you can use:
var sterling1Per = parseInt(sterling.value, 10) / 100;
If it's a float, you can use:
var sterling1Per = parseFloat(sterling.value) / 100;
Anywhere that you use an input .value that needs to be a number needs to be parsed accordingly

Javascript calculation tools is not working perfectly

I've a Javascript calculation tools which sometimes work and sometimes don't work. I don't understand why.
Here is my demo tools : http://propertyjungle.com.au/modern-business/tools_check.php
well, In my "Fixed agent cost when selling" tools there are 5 fields :
1) House Sale Price
2) Rate quoted by agent
3) Other Fees
And in "Result" part there are 2 fields:
1) Agent Fees:
2) Reducing the rate the agent is charging by 0.1% will save you
It's showing the result automatically. I mean on keypress.
So When I increment both "House Sales Price" and "Rate Quoted..." then both result fields is showing me "NaN". But it's should be show the value.. e.g:
House Sales Price = 10000
Rated Quoted = 0.3%
Other Fees = 0 (empty)
Result:
Agent Fees = 30 (House Sales Prices * Rated Quoted )
Reducing.... = 10 (0.1% of House sales Price)
After that If I increment "Other Fees" it's then showing the result but result is wrong. It's should be e.g :
Correct Result:
Agent Fees = 10030 (House Sales Prices * Rated Quoted + Other Fees[increment by 10,000] )
Reducing.... = 10 (0.1% of House sales Price)
Wrong Result :
Agent Fees = 10030 (House Sales Prices * Rated Quoted + Other Fees[increment by 10,000] )
Reducing.... = 10010.00
Here is my complete code:
Javascript:
function incrementValue()
{
var value = parseInt(document.getElementById('pvalue1').value, 10);
value = isNaN(value) ? 0 : value;
value +=10000
document.getElementById('pvalue1').value = value;
}
function decrementValue()
{
var value = parseInt(document.getElementById('pvalue1').value, 10);
value = isNaN(value) ? 0 : value;
value -=10000
document.getElementById('pvalue1').value = value;
}
function incrementValueO()
{
var value = parseInt(document.getElementById('otherFees').value, 10);
value = isNaN(value) ? 0 : value;
value +=10000
document.getElementById('otherFees').value = value;
$('#pvalue1').trigger("change");
}
function decrementValueO()
{
var value = parseInt(document.getElementById('otherFees').value, 10);
value = isNaN(value) ? 0 : value;
value -=10000
document.getElementById('otherFees').value = value;
}
function toggleIncrement()
{
var value = parseFloat(document.getElementById('pvalue2').value, 10);
value = isNaN(value) ? 0 : value;
value +=0.1
value = parseFloat(value).toFixed(2)
document.getElementById('pvalue2').value = value;
$('#pvalue1').trigger("change");
}
function toggleDecrement()
{
var value = parseFloat(document.getElementById('pvalue2').value, 10);
value = isNaN(value) ? 0 : value;
value -=0.1
value = parseFloat(value).toFixed(2)
document.getElementById('pvalue2').value = value;
$('#pvalue1').trigger("change");
}
jQuery(document).ready(function(){
$('#pvalue1').change(function(){
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
console.debug( parseFloat(document.getElementById('otherFees').value));
var otherFees = parseFloat(document.getElementById('otherFees').value);
var totalOtherFees = agentfee + otherFees;
$('#pvalue3').val(totalOtherFees);
var percentagereduce = parseFloat($('#pvalue2').val(), 10) - 0.1;
var newvalue = parseFloat($('#pvalue1').val(), 10) * percentagereduce / 100;
$('#pvalue4').val(newvalue);
var takevalue1 = parseFloat($('#pvalue3').val(), 10);
var takevalue2 = parseFloat($('#pvalue4').val(), 10);
var finalvalue = takevalue1 - takevalue2;
var finalvalue = parseFloat(finalvalue).toFixed(2)
$('#pvalue5').val(finalvalue);
});
$('#pvalue2').change(function(){
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
$('#pvalue3').val(agentfee);
var percentagereduce = parseFloat($('#pvalue2').val(), 10) - 0.1;
var newvalue = parseFloat($('#pvalue1').val(), 10) * percentagereduce / 100;
$('#pvalue4').val(newvalue);
var takevalue1 = parseFloat($('#pvalue3').val(), 10);
var takevalue2 = parseFloat($('#pvalue4').val(), 10);
var finalvalue = takevalue1 - takevalue2;
$('#pvalue5').val(finalvalue);
});
$('#otherFees').change(function(){
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
console.debug( parseFloat(document.getElementById('otherFees').value));
var otherFees = parseFloat(document.getElementById('otherFees').value);
var totalOtherFees = agentfee + otherFees;
$('#pvalue3').val(totalOtherFees);
var percentagereduce = parseFloat($('#pvalue2').val(), 10) - 0.1;
var newvalue = parseFloat($('#pvalue1').val(), 10) * percentagereduce / 100;
$('#pvalue4').val(newvalue);
var takevalue1 = parseFloat($('#pvalue3').val(), 10);
var takevalue2 = parseFloat($('#pvalue4').val(), 10);
var finalvalue = takevalue1 - takevalue2;
var finalvalue = parseFloat(finalvalue).toFixed(2)
$('#pvalue5').val(finalvalue);
});
});
Html Code:
<table border="0" cellpadding="5">
<tr>
<td>House Sale Price:</td>
<td>$</td>
<td><input name="pvalue1" class="form-control" onkeypress="validate(event)" placeholder=" Enter Sale Price" type="number" value="<?=$pvalue1?>" id="pvalue1" size="20" required ></td>
<td><input type="button" onClick="incrementValue()" value="+" /><input type="button" onClick="decrementValue()" value="-" /> </td>
</tr>
<tr>
<td>Rate quoted by agent:</td>
<td>%</td>
<td><input name="pvalue2" class="form-control" onkeypress="validate(event)" placeholder=" Percentage" type="number" value="<?=$pvalue2?>" id="pvalue2" size="20" required ></td>
<td><input type="button" onClick="toggleIncrement()" value="+" /><input type="button" onClick="toggleDecrement()" value="-" /></td>
</tr>
<tr>
<td>Other Fees</td>
<td>$</td>
<td><input name="otherFees" class="form-control" onkeypress="validate(event)" placeholder=" Enter Sale Price" type="number" value="<?=$pvalue1?>" id="otherFees" size="20" required ></td>
<td><input type="button" onClick="incrementValueO()" value="+" /><input type="button" onClick="decrementValueO()" value="-" /> </td>
</tr>
</table>
<input name="doRegister" type="submit" id="doRegister" value="Calculate" style="color:white;font-size:20px;" class="btn btn-primary">
<br><br>
<h2>Results</h2>
<table>
<tr>
<td>Agent Fees:</td>
<td>$</td>
<td><input name="pvalue3" onkeypress="validate(event)" class="form-control" placeholder="" type="number" value="<?=$pvalue3?>" id="pvalue3" size="10" class="resultfield" ></td></tr>
<tr>
<td></td>
<td><span id='show-me' class="form-control" style='display:none'><input name="pvalue4" placeholder="" type="number" value="<?=$pvalue4?>" id="pvalue4" size="10" class="resultfield" ></span></td></tr>
<tr>
<td>Reducing the rate the agent is charging by 0.1% will save you: </td>
<td>$</td>
<td><input name="pvalue5" onkeypress="validate(event)" class="form-control" placeholder="" type="number" value="<?=$pvalue5?>" id="pvalue5" size="10" class="resultfield" ></td>
</tr>
</table>
Many Thanks to you.
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
console.log($('#pvalue1').val()); //3
console.log( $('#pvalue2').val()); // ""
parseInt("") is NaN
You deal with isNaN in the code above, implement the same logic here.

Calculations between input boxes

I'm writing a script where I need to get the total of two calculations and determine the total quote. The problem is I cannot get them to work when it comes to add them together. Bear in mind I'm a newbie and the code might no be fully optimized but I'm sure you will get the point. Any improvements on the code are more than welcome.
<div>
<fieldset>
<legend>Printing</legend>
Number of color pages:<input type="text" id="color" placeholder="Color Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="colorprice" readonly="readonly" /><br />
Number of black and white pages:<input type="text" id="black" placeholder="Black and White Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="blackprice" readonly="readyonly" /><br />
Total Pages:<input type="text" id="pages_total" readonly="readonly" /> <input type="text" id="sum_pages" readonly="readonly" onchange = "suming();"/>
</fieldset>
</div>
<div>
<fieldset>
<legend>Binding</legend>
Number of Hardbooks: <input type="text" id="books" placeholder="Number of Hardbooks" onchange="binding();" />
<input type="text" id="books_price" readonly="readonly" /><br />
Number of Softbacks: <input type="text" id="softback" placeholder="Number of Softbacks" onchange="binding();" />
<input type="text" id="soft_price" readonly="readonly" /><br />
Total Bindings: <input type="text" id="total_bindings" readonly="readonly" /><input type "text" id="total_price" readonly="readonly" />
</fieldset>
</div>
<p>Final quote:<input type="text" readonly="readonly" id="quote" /></p>
function printing() {
var blackPrice;
var colorPrice;
var printBlack = new Array(0.10, 0.08, 0.06, 0.05);
var printColor = new Array(0.40, 0.35, 0.30, 0.25);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (colorPages < 11) {
colorPrice = colorPages * printColor[0];
}
else if (colorPages >= 11 && colorPages < 51){
colorPrice = colorPages * printColor[1];
}
else if (colorPages >= 51 && colorPages < 101){
colorPrice = colorPages * printColor[2];
}
else {
colorPrice = colorPages * printColor[3];
}
if (blackPages < 11) {
blackPrice = blackPages * printBlack[0];
}
else if (blackPages >= 11 && colorPages < 51){
blackPrice = blackPages * printBlack[1];
}
else if (blackPages >= 51 && colorPages < 101){
blackPrice = blackPages * printBlack[2];
}
else {
blackPrice = blackPages * printBlack[3];
}
var pagesTotal = colorPages + blackPages;
var printSum = blackPrice + colorPrice;
document.getElementById("colorprice").value = "$" + colorPrice.toFixed(2);
document.getElementById("blackprice").value = "$" + blackPrice.toFixed(2);
document.getElementById("sum_pages").value = "$" + printSum.toFixed(2);
document.getElementById("pages_total").value = pagesTotal;
return printSum;
}
function binding(){
var softbackPrice;
var hardbookPrice;
var hardBooks = new Array(37.50, 23.50);
var softBacks = new Array(3.75, 4.00, 4.25, 4.50, 4.75, 5.00, 5.25);
var noBooks = parseInt(document.getElementById("books").value);
var noSoftBacks = parseInt(document.getElementById("softback").value);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
var totalPages = colorPages + blackPages;
if (noBooks == 1) {
hardbookPrice = hardBooks[0];
}
else {
hardbookPrice = (hardBooks[1] * (noBooks - 1)) + hardBooks[0];
}
if (totalPages <= 50) {
softbackPrice = softBacks[0] * noSoftBacks;
}
else if (totalPages > 50 && totalPages <= 100) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 100 && totalPages <= 150) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 150 && totalPages <=200) {
softbackPrice = softBacks[2] * noSoftBacks;
}
else if (totalPages > 200 && totalPages <= 250) {
softbackPrice = softBacks[3] * noSoftBacks;
}
else if (totalPages > 250 && totalPages <= 300) {
softbackPrice = softBacks[4] * noSoftBacks;
}
else if (totalPages > 300 && totalPages <= 350) {
softbackPrice = softBacks[5] * noSoftBacks;
}
else {
softbackPrice = softBacks[6] * noSoftBacks;
}
var totalPrice = softbackPrice + hardbookPrice;
var bindingsTotal = noSoftBacks + noBooks;
document.getElementById("books_price").value = "$" + hardbookPrice.toFixed(2);
document.getElementById("soft_price").value = "$" + softbackPrice.toFixed(2);
document.getElementById("total_bindings").value = bindingsTotal;
document.getElementById("total_price").value = "$" + totalPrice.toFixed(2);
return totalPrice;
}
function totalSum() {
var totalPrinting = printing();
var totalBinding = binding();
var subtotal = totalPrinting + totalBinding;
document.getElementIdBy("quote").value = subtotal;
}
Here is the working solution. http://jsfiddle.net/UHnRL/2/
= is missing for type in the below markup
<input type "text" id="total_price" readonly="readonly" />
It works for me (mostly): http://jsfiddle.net/UHnRL/
There is an issue with the first onchange calculation, because the other number of pages is NaN after you do the parseInt. You should default it to zero if the text box is blank.
You can use the isNaN[MDN] function to resolve the calculation issue:
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (isNaN(colorPages))
{
colorPages = 0;
}
if (isNaN(blackPages))
{
blackPages = 0;
}

Categories

Resources