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';
}
Related
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);
}
Really struggling with this part for some reason.
I'm creating a timer I can use to keep track of bids. I want to be able to compare two times and have the difference (in minutes and seconds) shown in the countdown column. It should be comparing the bid start time and the time right now.
Perhaps when it reaches bid start it could also change to show how long until bid ends. Eventually I want to add background changes once it's getting close to the time, and perhaps the ablility to set alarms with a prompt window.
Here's the code I have so far:
HTML
<table>
<tr>
<td>Item Name</td>
<td><input id="itemNameField" placeholder="" type="text"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Time of Notice</td>
<td><input id="noticeField" type="time"></td>
</tr>
</table>
<input id="addButton" onclick="insRow()" type="button" value="Add Timer">
<div id="errorMessage"></div>
<hr>
<div id="marketTimerTableDiv">
<table border="1" id="marketTimerTable">
<tr>
<td></td>
<td>Item Name</td>
<td>Time of Notice</td>
<td>Bid Start</td>
<td>Bid End</td>
<td>Countdown</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div id="itembox"></div>Example Item
</td>
<td>
<div id="noticebox"></div>12:52
</td>
<td>
<div id="bidstartbox"></div>13:02
</td>
<td>
<div id="bidendbox"></div>13:07
</td>
<td>
<div id="countdownbox"></div>
</td>
<td><input id="delbutton" onclick="deleteRow(this)" type="button" value="X"></td>
</tr>
</table>
</div>
JAVASCRIPT
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
if (i == 1) {
console.log = "hi";
} else {
document.getElementById('marketTimerTable').deleteRow(i);
}
}
function insRow() {
if (itemNameField.value == "" || noticeField.value == "") {
var div = document.getElementById('errorMessage');
div.innerHTML = "*Please fill in the fields*";
div.style.color = 'red';
document.body.appendChild(div);
} else {
var div = document.getElementById('errorMessage');
div.innerHTML = "";
var x = document.getElementById('marketTimerTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var inp1 = new_row.cells[1].getElementsByTagName('div')[0];
inp1.id += len;
inp1.innerHTML = itemNameField.value;
itemNameField.value = "";
var inp2 = new_row.cells[2].getElementsByTagName('div')[0];
inp2.id += len;
inp2.innerHTML = noticeField.value;
noticeField.stepUp(10);
var inp3 = new_row.cells[3].getElementsByTagName('div')[0];
inp3.id += len;
inp3.innerHTML = noticeField.value;
noticeField.stepUp(5);
var inp4 = new_row.cells[4].getElementsByTagName('div')[0];
inp4.id += len;
inp4.innerHTML = noticeField.value;
var inp5 = new_row.cells[5].getElementsByTagName('div')[0];
inp5.id += len;
inp5.innerHTML = "";
noticeField.value = "";
x.appendChild(new_row);
}
}
I apologize in advance because my code is probably really messy and badly formatted. Here's a JSFIDDLE as well! Thanks :)
To calculate the difference between the current and given time, you can use setInterval
Example :
var noticeTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
var diffInHours = currentDate.getHours() - noticeTime[0];
var diffInMinutes = currentDate.getMinutes() - noticeTime[1];
inp5.innerHTML = diffInHours + ":" + diffInMinutes;
if(diffInHours === 0 && diffInMinutes === 0) {
clearInterval(interval);
}
},1000)
I managed to do it with the help of the code from ProgXx.
I added the following code:
var noticeTime = noticeField.value.split(":");
var originalTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
noticeTime[1] = originalTime[1] - currentDate.getMinutes() + 10;
noticeTime[1] = noticeTime[1] + (originalTime[0] * 60) - (currentDate.getHours() * 60);
Here's a JSFIDDLE of the finihsed code: http://jsfiddle.net/joefj8wb/
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
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.
I am somewhat new to Javascript and I'm trying to make a basic calculator that has 3 text inputs, a 1st number text box, an operation textbox, and a second number textbox, but it doesn't print out the text when I click a button or use any other method to trigger the event.
This is my code:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if(B == "+")
{
D = A+C;
}
elseif(B == "-")
{
D = A-C;
}
elseif(B == "*")
{
D = A*C;
}
elseif(B == "/")
{
D = A/C;
}
document.getElementById("result").innerHTML = D;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onclick="calc()" />
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I'd suggest the following (explanations commented in the code itself):
function calc() {
/* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...)
or innerText (Microsoft) to set the text of an element/node */
var textType = Node.textContent ? 'textContent' : 'innerText',
/* uses parseFloat to create numbers (where possible) from the entered value
if parseFloat fails to find a number (it's empty or nonsensical)
then a 0 is used instead (to prevent NaN being the output). */
num1 = parseFloat(document.getElementById('num1').value) || 0,
num2 = parseFloat(document.getElementById('num2').value) || 0,
// retrieves the result element
result = document.getElementById('result');
// switch is used to avoid lots of 'if'/'else if' statements,
// .replace() is used to remove leading, and trailing, whitespace
// could use .trim() instead, but that'd need a shim for (older?) IE
switch (document.getElementById('op').value.replace(/\s/g,'')){
// if the entered value is:
// a '+' then we set the result element's text to the sum
case '+':
result[textType] = num1 + num2;
break;
// and so on...
case '-':
result[textType] = num1 - num2;
break;
case '*':
result[textType] = num1 * num2;
break;
case '/':
result[textType] = num1 / num2;
break;
// because people are going to try, give a default message if a non-math
// operand is used
default:
result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.'
break;
}
}
JS Fiddle demo.
References:
parseFloat().
switch () {...}.
I would have done things a bit differently, but to answer your question and just get your code working I did the following:
Here is your reworked code:
<html>
<script>
function calc(form) {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = D;
return false;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onClick="calc(this)">
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I used the parseint() because your expressions in your if statements were treating values like text.
Next we need to use === Three equals which says A is really equal to + or what ever the second input value is.
Third was the onclick, I did a (this) and feed back form as you can see in the line that says function calc.
For good measure I added a return false; to prevent form submission (but it will function without it).
Also like other posters stated it is else if and not elseif.
I hope this is helpful. Again, I would do things differently but got it working with some explanations.
I recommend using eval()
If the user inputs "5+6" or "(9*3)/5" and you set that to a variable, eval() will parse and solve the problem!
It's else if not elseif. Also you need to use parseInt on A+C, otherwise it will treat your strings as...well, strings. You should have seen the elseif error in your browser. Are you using something like firebug? If you aren't, start. Let tools do the hard work for you.
There is a way you can do it with a single input box:
function findOps(s) {
for (var i = 0; i < s.length; i++) {
if (s[i] == "+")
return "+";
if (s[i] == "-")
return "-";
if (s[i] == "*")
return "*";
if (s[i] == "/")
return "/";
}
}
var input = '';
function calc() {
var dom = $("#input");
input = dom.val();
try {
switch (findOps(input)) {
case "+":
var a = input.split("+");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x + y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "-":
var a = input.split("-");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x - y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "*":
var a = input.split("*");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x * y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "/":
var a = input.split("/");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x / y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
}
} catch (err) {
alert("catched¡");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amanpreet singh</title>
</head>
<body>
<center>
<table cellpadding="10" cellspacing="10" style="font-size:2em">
<tr><td>Number 1:</td>
<td><input type="text" id="num1" name="num1" /></td>
</tr>
<tr><td>Number 2:</td>
<td> <input type="text" id="num2" name="num2" /></td>
</tr>
<tr>
<td> <label for=" Operator"> Operator:</label></td>
<td> <select name="Operator" id="op" name="op">
<option value="+">Add</option> <option value="-">Subtract</option>
<option value="*">Muliply</option><option value="/">Divide</option>
</select></td>
</tr>
<tr><td colspan="2" align="cover">
<center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>