javascript calculation grand total result become double - javascript

I am trying to develop a simple accounting calculator.
Maybe the word calculator would be more vast according to my project nature. In fact it is simple transaction calculation.
First fall it deals with
item rate
item qnt
total amnt of each item (rate*qnt)
I did it, now all row amnt should be sum and set result as Grand total with condition - the requirement. Indeed, I can't handle this condition.
condition can be
discount
tax
to the sum of total items user can apply discount(+), tax(%), loss(-) whatever he wish, I am able to get result of these conditions also, but while merging result or to get grand total, it becomes mess and output in grand total comes randomly.
For example, user bought
item qnt rate amnt
pen 1200 2 2400
copy 200 20 4000
Now
13% vat included + (//user can enter with % sigh, amount would be 492)
200 Discount got - 200
Grand total should be 6692
My result is 8172.16 almost double. I prefer pure JavaScript, if it is becomes more easier with Jquery is also good.
window.onload=function(){
itm_qnt_rte();
dsc_vat();
}
function itm_qnt_rte(){
var rte = document.querySelectorAll('.rte');
for(var i=0;i<rte.length;i++){
rte[i].onchange=function(){
var rate = parseInt(this.value);
var qnt = parseInt(this.closest('tr').querySelector('.qnt').value);
if(rate > 0 && qnt >0){
var amnt = rate*qnt;
this.closest('tr').querySelector('.amnt').value = amnt;
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
}
var qnt = document.querySelectorAll('.qnt');
for(var i=0;i<qnt.length;i++){
qnt[i].onchange=function(){
var qnt = parseInt(this.value);
var rte = parseInt(this.closest('tr').querySelector('.rte').value);
if(rte > 0 && qnt >0){
var amnt = rte*qnt;
this.closest('tr').querySelector('.amnt').value = amnt;
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
}
}
function dsc_vat(){
var dsc_vat = document.querySelectorAll('.dv');
for(var a=0;a<dsc_vat.length;a++){
dsc_vat[a].onchange = function(){
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
}
var selected = this.closest('table').querySelectorAll('.dv');
for(var b=0;b<selected.length;b++){
var value = this.value;
var gttl = 0;
if (value !== '') {
if (value[value.length - 1] === '%') {
gttl = ((sum * parseInt(value)) / 100);
}
if (value[value.length - 1] !== '%') {
gttl = parseInt(value);
}
var n = gttl * 1;
if (n >= 0) {
sum = sum + gttl
} else {
sum = sum - Math.abs(gttl);
}
}
if (value == '' || value === '0') {
this.value=0;
}
this.closest('tr').querySelector('.dv_amnt').value = gttl;
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
.txtcenter{
text-align:center
}
.txtright{
text-align:right
}
.g_ttl{
border:2px solid red;
}
table{
margin-bottom:50px;
}
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Particulars</th><th>Qnt</th><th>Rate</th><th>amnt</th>
</tr>
<tr>
<td>Pen</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td>Pencil</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Discount</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Tax</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr><td colspan='3'>Grand Total</td><td><input type='text' class='g_ttl' /></td></tr>
</table>
Table 2
<table>
<tr>
<th>Particulars</th><th>Qnt</th><th>Rate</th><th>amnt</th>
</tr>
<tr>
<td>Pen</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td>Pencil</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Discount</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Tax</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr><td colspan='3'>Grand Total</td><td><input type='text' class='g_ttl' /></td></tr>
</table>
</body>
</html>

Ok here goes my explanation.
There are a few logic flaws which we have to take care of first.
1) You are using the same function to calculate discount and tax. And discount needs to be subtracted from the sum not added. Hece, I multiplied the discount value by -1.
2) The reason you were getting the sum as almost double is because you used the class dv for both discount and tax due to which the length was calculated as 2 instead of 1.
3) I have added a routine to calculate the tax separately and used a class 'dv_tax' specifically for tax calculation
I have made an assumption that the tax calculation is done after the discount is applied.
Note: In case of your program, the user needs to input all values in sequential order to calculate the discount and tax correctly i.e after adding discount or tax, if the user decides to change the input rate or qty he has to delete the tax and discount rates and key it in again. You can use additional onChange functions to recalculate tax and discount when any of the value changes.
HTML
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Particulars</th><th>Qnt</th><th>Rate</th><th>amnt</th>
</tr>
<tr>
<td>Pen</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td>Pencil</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Discount</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt total_discount' /></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Tax</td><td><input type='text' class='dv_tax' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr><td colspan='3'>Grand Total</td><td><input type='text' class='g_ttl' /></td></tr>
</table>
Table 2
<table>
<tr>
<th>Particulars</th><th>Qnt</th><th>Rate</th><th>amnt</th>
</tr>
<tr>
<td>Pen</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td>Pencil</td><td><input type='text' class='qnt'></td><td><input type='text' class='rte' /></td>
<td><input type='text' class='amnt'></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Discount</td><td><input type='text' class='dv' /></td><td><input type='text' class='dv_amnt total_discount' /></td>
</tr>
<tr>
<td colspan='2' class='txtcenter'>Tax</td><td><input type='text' class='dv_tax' /></td><td><input type='text' class='dv_amnt' /></td>
</tr>
<tr><td colspan='3'>Grand Total</td><td><input type='text' class='g_ttl' /></td></tr>
</table>
</body>
</html>
Javascript
window.onload=function(){
itm_qnt_rte();
dsc_vat();
tax_vat();
}
function itm_qnt_rte(){
var rte = document.querySelectorAll('.rte');
for(var i=0;i<rte.length;i++){
rte[i].onchange=function(){
var rate = parseInt(this.value);
var qnt = parseInt(this.closest('tr').querySelector('.qnt').value);
if(rate > 0 && qnt >0){
var amnt = rate*qnt;
this.closest('tr').querySelector('.amnt').value = amnt;
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
}
var qnt = document.querySelectorAll('.qnt');
for(var i=0;i<qnt.length;i++){
qnt[i].onchange=function(){
var qnt = parseInt(this.value);
var rte = parseInt(this.closest('tr').querySelector('.rte').value);
if(rte > 0 && qnt >0){
var amnt = rte*qnt;
this.closest('tr').querySelector('.amnt').value = amnt;
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
}
}
function dsc_vat(){
var dsc_vat = document.querySelectorAll('.dv');
for(var a=0;a<dsc_vat.length;a++){
dsc_vat[a].onchange = function(){
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
}
var selected = this.closest('table').querySelectorAll('.dv');
for(var b=0;b<selected.length;b++){
var value = this.value;
var gttl = 0;
if (value !== '') {
if (value[value.length - 1] === '%') {
gttl = ((sum * parseInt(value)) / 100);
gttl = gttl*-1;
}
if (value[value.length - 1] !== '%') {
gttl = parseInt(value);
gttl = gttl*-1;
}
var n = gttl * 1;
if (n >= 0) {
sum = sum + gttl
} else {
sum = sum - Math.abs(gttl);
}
}
if (value == '' || value === '0') {
this.value=0;
}
this.closest('tr').querySelector('.dv_amnt').value = Math.abs(gttl);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}
function tax_vat(){
var tax_vat = document.querySelectorAll('.dv_tax');
for(var a=0;a<tax_vat.length;a++){
tax_vat[a].onchange = function(){
var sum = 0;
var g_ttl = this.closest('table').querySelectorAll('.amnt');
for(k=0;k<g_ttl.length;k++){
var value = parseInt(g_ttl[k].value);
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
}
var disc_select = this.closest('table').querySelectorAll('.total_discount');
sum = sum - disc_select[0].value;
var selected = this.closest('table').querySelectorAll('.dv_tax');
for(var b=0;b<selected.length;b++){
var value = this.value;
var gttl = 0;
if (value !== '') {
if (value[value.length - 1] === '%') {
gttl = ((sum * parseInt(value)) / 100);
}
if (value[value.length - 1] !== '%') {
gttl = parseInt(value);
}
var n = gttl * 1;
if (n >= 0) {
sum = sum + gttl
} else {
sum = sum - Math.abs(gttl);
}
}
if (value == '' || value === '0') {
this.value=0;
}
this.closest('tr').querySelector('.dv_amnt').value = Math.abs(gttl);
}
this.closest('table').querySelector('.g_ttl').value = sum;
}
}
}

Related

Create a loop to calculate average scores

I would like to calculate the class average and wanted to store the inputs in different variables. However, the scores are calculating together at once and I have trouble fixing it. Do I use a for loop to repeat the equation? Please help me ! Thanks
Here is my codepen to the code:
https://codepen.io/ivy-chung/pen/GBzmwb?editors=1010
$(document).ready(function() {
//iterate through each textboxes
$('.txtMarks').each(function() {
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function() {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value <= 30) {
calcGradeScore();
} else {
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore() {
var total = 0;
var average = 0;
var avgGrade;
var img = document.createElement("img");
//iterate through each textboxes with class name '.txtMarks'and add the values.
$('.txtMarks').each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = $('.txtMarks').length;
average = parseFloat(total) / (txtboxes * 0.3);
}
if (average >= 80 && average < 100) {
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
} else if (average >= 70 && average < 79) {
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
} else if (average >= 60 && average < 69) {
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
} else if (average >= 50 && average < 59) {
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
} else if (average >= 0 && average < 49) {
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
$('#totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
$('#average').html(average.toFixed(1) + "%");
// S
$('#grade').html(avgGrade);
//
$('#image').html(img);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Grade Calculator</h1>
<table class="grade-table">
<tr class="label">
<td colspan="2">Please enter student's classwork score out of 30:</td>
</tr>
<tr>
<td>Subject 1:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 2: </td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 3:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr class="label">
<td class="right">Total Marks :</td>
<td class="center"><span id="totalMarks">0</span></td>
</tr>
<tr class="label">
<td class="right">Average Percentage :</td>
<td class="center"><span id="average">0</span></td>
</tr>
<tr class="label">
<td class="right">Grade:</td>
<td class="center"><span id="grade">0</span></td>
</tr>
<tr class="label">
<td class="right"></td>
<td class="center"><span id="image"></span></td>
</tr>
</table>
<table class="grade-table">
<tr class="label">
<td colspan="2">Please enter student's classwork score out of 30:</td>
</tr>
<tr>
<td>Subject 1:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 2: </td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr>
<td>Subject 3:</td>
<td>
<input type="text" class="txtMarks" name="txtMarks" maxlength="4" /></td>
</tr>
<tr class="label">
<td class="right">Total Marks :</td>
<td class="center"><span id="totalMarks">0</span></td>
</tr>
<tr class="label">
<td class="right">Average Percentage :</td>
<td class="center"><span id="average">0</span></td>
</tr>
<tr class="label">
<td class="right">Grade:</td>
<td class="center"><span id="grade">0</span></td>
</tr>
<tr class="label">
<td class="right"></td>
<td class="center"><span id="image"></span></td>
</tr>
</table>
As your are using duplicate id for Total Marks, Average Percentage, Grade and image, so instead of using duplicate id use class name and access by
$(this).closest('table').find('.classname')
So will provide you current table element and calculation will be reflect for that particular table.
Working codepen
CODE SNIPPET
$(document).ready(function() {
//iterate through each textboxes
$('.txtMarks').each(function() {
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function() {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value <= 30) {
calcGradeScore($(this).closest('table'));
} else {
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore(el) {
var total = 0,
average = 0,
avgGrade,
img = document.createElement("img"),
txtMarks = el.find('.txtMarks');
//iterate through each textboxes with class name '.txtMarks'and add the values.
txtMarks.each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = txtMarks.length;
average = parseFloat(total) / (txtboxes * 0.3);
}
if (average >= 80 && average < 100) {
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
} else if (average >= 70 && average < 79) {
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
} else if (average >= 60 && average < 69) {
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
} else if (average >= 50 && average < 59) {
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
} else if (average >= 0 && average < 49) {
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
el.find('.totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
el.find('.average').html(average.toFixed(1) + "%");
// S
el.find('.grade').html(avgGrade);
//
el.find('.image').html(img);
}
you can add the parent selector to calculate the average for each table
<table class="grade-table" id="table1">....</div>
<table class="grade-table" id="table2">....</div>
$(document).ready(function () {
//iterate through each textboxes
$('.txtMarks').each(function(){
// call 'calcSumAndAverage' method on keyup handler.
$(this).keyup(function () {
// check value is within range and is a number
if (!isNaN(this.value) && this.value.length != 0 && this.value >= 0 && this.value<=30) {
calcGradeScore('#'+this.parentElement.parentElement.parentElement.parentElement.id); // td > tr > tbody > table
}else{
alert("Wrong number, number must be 0-30");
}
});
});
});
function calcGradeScore($parentSelector) {
var total = 0;
var average = 0;
var avgGrade;
var img = document.createElement("img");
//iterate through each textboxes with class name '.txtMarks'and add the values.
$($parentSelector +' .txtMarks').each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0 ) {
total += parseFloat(this.value);
}
console.log(total);
});
//Calculate the Average
if (!isNaN(total) && total != 0) {
//Get count of textboxes with class '.txtMarks'
var txtboxes = $($parentSelector +' .txtMarks').length;
average = parseFloat(total) / (txtboxes*0.3);
}
if(average >= 80 && average < 100){
avgGrade = 'HD-High Distiction';
img.src = "https://memegenerator.net/img/instances/19226146/first-assestment-of-the-year-gets-high-distinction.jpg";
}
else if(average >= 70 && average < 79){
avgGrade = 'D-Distiction';
img.src = "https://memegenerator.net/img/instances/53639165/distinction-why-not-high-distinction.jpg";
}
else if(average >= 60 && average < 69){
avgGrade = 'C-Credit';
img.src = "https://pics.me.me/the-face-you-make-cjthecreditfixer-when-you-check-your-credit-27495760.png";
}
else if(average >= 50 && average < 59){
avgGrade = 'P-Pass';
img.src = "http://images.memes.com/meme/535301";
}
else if(average>= 0 && average < 49){
avgGrade = 'F-Failed';
img.src = "https://www.36ng.ng/wp-content/uploads/2015/09/Exam-fail-3.jpg";
}
//Show Total Marks.
$($parentSelector +' #totalMarks').html(total);
// Show Average upto 2 decimal places using .toFixed() method.
$($parentSelector +' #average').html(average.toFixed(1) + "%");
// S
$($parentSelector +' #grade').html(avgGrade);
//
$($parentSelector +' #image').html(img);
}

JavaScript GPA calculator isn't reading user inputs

I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can't find out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc() {
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++) {
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++) {
if (ingr[x] == gr[xx]) {
allgr = allgr + (parseInt(incr[x], 10) * cr[xx]);
allcr = allcr + parseInt(incr[x], 10);
validgrcheck = 1;
break;
}
}
if (validgrcheck == 0) {
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0) {
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name="GPACalcForm">
<table border="2" bgcolor="#bb8fce" cellpadding="5" cellspacing="2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type="text" size="5" name="GR1" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR1" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type="text" size="5" name="GR2" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR2" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type="text" size="5" name="GR3" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR3" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type="text" size="5" name="GR4" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR4" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type="text" size="5" name="GR5" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR5" align="top" maxlength="5"></TD>
</TR>
<TR>
<TR align="center">
<TD colspan="3">
<input type="button" value="Calculate" name="CalcButton" OnClick="gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can figure out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc()
{
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
console.log(ingr[0]);
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++)
{
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++)
{
if (ingr[x] == gr[xx])
{
allgr = allgr + (parseInt(incr[x],10) * cr[xx]);
allcr = allcr + parseInt(incr[x],10);
validgrcheck = 1;
break;
}
}
console.log(validgrcheck);
if (validgrcheck == 0)
{
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0)
{
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name = "GPACalcForm">
<table border = "2" bgcolor = #bb8fce cellpadding = "5" cellspacing = "2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type = "text" size = "5" name = "GR1" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR1" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type = "text" size = "5" name = "GR2" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR2" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type = "text" size = "5" name = "GR3" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR3" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type = "text" size = "5" name = "GR4" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR4" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type = "text" size = "5" name = "GR5" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR5" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TR align = "center">
<TD colspan = "3">
<input type = "button" value = "Calculate" name = "CalcButton" OnClick = "gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I have made the following change in your code :-
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
to
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}

Dynamically change the color or text based on value with Javascript

Hey guys looking for some assistance with changing the color of text based on value. If the value is zero or negative I want it to be red, and if the value is + I want it to be green. Below is just a little bit of code from the full html but I think these are the key parts. Here is a JSFiddle As you can see the table is dynamic. As you input data into the starting amount it will automatically calculate it for the ending amount. The starting amount adds to the bill amount which produces the total amount number. I am also not sure if the event "onchange" is correct. Thank you for your input and advise in advanced.
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt" onchange="colorChange(this)">0</span></b></p>
<script type="text/Javascript">
var myElement = document.getElementById('totalAmt');
function colorChange() {
if('myElement' > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt') ;
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
}
</script>
You can reach the desired result using just one function. Instead of checking the DOM element's innerHTML or textContext to get the amount, just refer to the variables holding it.
var myElement = document.getElementById('totalAmt');
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
myElement.style.color = money + billTotal <= 0 ? 'red' : 'green';
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
use myElement.innerHTML instead of myElement in the if condition and invoke the changeColor function at last of calc
var myElement = document.getElementById('totalAmt');
function colorChange() {
if (myElement.innerHTML <= 0) {
totalAmt.style.color = 'red';
} else {
totalAmt.style.color = 'green';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange();
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
A couple issues with your original code:
1 - you were checking if the string myElement was greater than zero, instead of the innerHTML of the element you selected.
2 - using innerHTML() to change the contents of an element doesn't fire an onchange event. In my code, I call your colorChange function at the end of the calc function, so if you decide to add another field to it (tax or something), it will be called after the total is calculated.
function colorChange() {
var myElement = document.getElementById('totalAmt');
if (myElement.innerHTML > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange()
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>

Javascript Range, Variance, and Standard Deviation Functions

So, I've been recently tasked to do a few calculations and to build a custom JS statistics library. The only 3 things I have left are to create functions for the range, variance, and standard deviation. What I'm doing here is passing my array (x) into the js functions, but they keep coming up blank. Am I doing something wrong?
function findSum(x)
{
var sum = 0;
for(i = 0; i < x.length; i++)
{
sum = sum + x[i];
}
return sum;
};
function findMean(x)
{
return findSum(x) / x.length;
};
function findMedian(x)
{
x.sort( function(a,b) {return a - b;} );
var half = Math.floor(x.length/2);
if(x.length % 2)
return x[half];
else
return (x[half-1] + x[half]) / 2.0;
}
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
};
function findMode(x)
{
var arrLen = x.length;
var _arr = x.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
function findRange(x)
{
x.sort( function (a, b) {return a-b;} );
}
function findVariance(x) {
var mean = findMean(x);
return findMean(array.map(findSum(sum)) {
return Math.pow(sum - mean, 2);
}));
},
function findStandardDeviation(x)
{
return Math.sqrt(findVariance(x));
};
The HTML code:
<html>
<head>
<h1>Statistical Calculations</h1>
<title>Calculating Stats</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='Stats.js'></script>
<script language="JavaScript">
function addNumber()
{
var input = document.getElementById('input').value;
var list = document.getElementById('list');
var option = document.createElement('OPTION');
list.options.add(option);
option.text = input;
}
function getStatistics()
{
var list = new Array();
var select = document.getElementById('list');
for(i = 0; i < select.options.length; i++)
{
list[i] = parseInt(select.options[i].text);
}
document.getElementById('summation').value =findSum(list);
document.getElementById('mean').value = findMean(list);
document.getElementById('median').value = findMedian(list);
document.getElementById('mode').value = findMode(list);
document.getElementById('variance').value = findVariance(list);
document.getElementById('standardDev').value = findStandardDeviation(list);
document.getElementById('range').value = findRange(list);
document.getElementById('max').value = findMax(list);
document.getElementById('min').value = findMin(list);
}
</script>
</head>
<body>
<table>
<tr>
<td>Input Number:</td><td><input type='text' id='input'></td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Add Number' onClick='addNumber()'></td>
</tr>
<tr>
<td colspan='2'>
<select id='list' size='5'>
</select>
</td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Calculate!' onClick='getStatistics()'></td>
</tr>
<tr>
<td>Summation:</td><td><input type='text' id='summation' readonly></td>
</tr>
<tr>
<td>Mean:</td><td><input type='text' id='mean' readonly></td>
</tr>
<tr>
<td>Median:</td><td><input type='text' id='median' readonly> </td>
</tr>
<tr>
<td>Mode:</td><td><input type='text' id='mode' readonly></td>
</tr>
<tr>
<td>Max:</td><td><input type='text' id='max' readonly></td>
</tr>
<tr>
<td>Min:</td><td><input type='text' id='min' readonly></td>
</tr>
<tr>
<td>Range:</td><td><input type='text' id='range' readonly></td>
</tr>
<tr>
<td>Variance:</td><td><input type='text' id='variance' readonly></td>
</tr>
<tr>
<td>Standard Deviation:</td><td><input type='text' id='standardDev' readonly></td>
</tr>
</table>
</body>
</html>
The last 3 seem to do absolutely nothing, and I've been bashing my head in for the last few days trying to figure it out. If anyone could help sort my functions out into working order, it'd be greatly appreciated! I'm sure that the array has been passing into the functions correctly, seeing as the first 4 functions obviously worked.

js - how to default to a specific value if target value does not met

I'm sorry to post this question but I'm kinda newbie when it comes to js. I have created a simple page that will compute charging transactions, so what it will do is to simply multiply the Quantity and Price to .25%. But here is the trick, if the total product is less than 50 the Charge field should default to 50 and that's where I'm kinda lost,
here is my code:
<tr>
<td width="144">Quantity:</td>
<td width="63"><input type="text" name="quantity" id="quantity" size="8"/></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" size="8"/></td>
</tr>
<tr>
<td colspan="4"><strong>Charges:</strong></td>
</tr>
<tr>
<td>Charge:</td>
<td><input style="color:#F00" type="text" name="charge" id="charge" size="8" readonly="readonly" /></td>
<td colspan="2">Quantity x Price x .25% OR 20 whichever is higher</td>
</tr>
here is the js that i managed to have,
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
$("#charge").val((q * p * 0.0025).toFixed(3)); // Charge
});
});
Put the total in a variable and test it before putting it into the DOM:
$(function () {
$("#quantity, #price").keyup(function () {
var q = parseFloat($("#quantity").val()); // Quantity
var p = parseFloat($("#price").val()); // Price
if (isNaN(q) || isNaN(p) || q<=0 || p <= 0) {
$("#charge").val('');
return false;
}
var total = q * p * 0.0025;
if (total < 50) {
total = 50;
}
$("#charge").val(total.toFixed(3)); // Charge
});
});
Another way is to use Math.max():
$("#charge").val(Math.max(50, q * p * 0.0025).toFixed(3)); // Charge

Categories