Create a loop to calculate average scores - javascript

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);
}

Related

Changing value of input range not updating content on mobile

I have an HTML input range that uses JS to change the text content of a table below it based on the value of the input range. It is working on Desktop but on Mobile the content will be stuck at the specified content for value = 1 and won't change to 2, 3, and 4. Any ideas? Thank you!
<div class="range-wrap">
<input type="range" class="range" id="slide" value="1" min="1" max="4" />
<output class="bubble"></output>
</div>
<h3 class="you-will">Every week you will save...</h3>
<table class="save">
<tr>
<td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-01.png" alt="time" / ></td>
<td class="eco-text"><strong><span id="time"></span></strong> <span>Spend time outdoors!</span></td>
</tr>
<tr>
<td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-02.png" alt="water" / ></td>
<td class="eco-text"><strong><span id="water"></span></strong> <span>Save the environment.</span></td>
</tr>
<tr>
<td><img class="eco-icon" src="https://www.happynest.com/hubfs/14500231/eco-icons-03.png" alt="electricity" / ></td>
<td class="eco-text"><strong><span id="electric"></span></strong> <span>Save some money.</span></td>
</tr>
</table>
JS
function updateSlider() {
var value = $("#slide").val();
if (value == 1) {
$("#time").text("4 hours of time.");
$("#water").text("60 gallons of water.");
$("#electric").text("$5 in electric bills.");
} else if (value == 2) {
$("#time").text("8 hours of time.");
$("#water").text("120 gallons of water.");
$("#electric").text("$10 in electric bills.");
} else if (value == 3) {
$("#time").text("12 hours of time.");
$("#water").text("180 gallons of water.");
$("#electric").text("$15 in electric bills.");
} else if (value == 4) {
$("#time").text("16 hours of time.");
$("#water").text("240 gallons of water.");
$("#electric").text("$20 in electric bills.");
}
}
updateSlider();
$('#slide').mousemove(updateSlider);
const allRanges = document.querySelectorAll(".range-wrap");
allRanges.forEach(wrap => {
const range = wrap.querySelector(".range");
const bubble = wrap.querySelector(".bubble");
range.addEventListener("input", () => {
setBubble(range, bubble);
});
setBubble(range, bubble);
});
function setBubble(range, bubble) {
const val = range.value;
const min = range.min ? range.min : 0;
const max = range.max ? range.max : 100;
const newVal = Number(((val - min) * 100) / (max - min));
bubble.innerHTML = val;
// Sorta magic numbers based on size of the native UI thumb
bubble.style.left = `calc(${newVal}% + (${8 - newVal * 1.5}px))`;
}
The input range is changing the table's content on Desktop but not mobile

After form is submitted, function runs quickly and chart shows up for a millisecond and then goes away

I have a JavaScript code that I have been trying for a while, where I am trying to get an input text/num with spaces in between and shows a graph of how many "students" received different grades letters. Everything is working great until the last part of the index.js code. When the user writes the scores numbers and clicks the submit button, the graph just shows for a millisecond the information and styles but then it seems like it re-loads again to the beginning. Please help me with the last function.
index.html
<body>
<h1>Grade Distribution</h1>
<div class="center">
<table id="distributionTable">
<tr id="firstRow">
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>F</td>
</tr>
<tr id="thirdRow">
</tr>
</table>
</div>
<section class="center2">
<form id=" ">
<div class="container">
<label class="label-title" for="scores-input">Enter the scores for each studente with space in between: </label>
<input type="text" id="scores-input">
<button onclick="fn1()" id="btn1">Submit</button>
</div>
</form>
</section>
index.js
function parseScores(scoresString) {
return scoresString.split(" "); //Return parsing
}
function buildDistributionArray(scoresArray) {
var result = [0, 0, 0, 0, 0]; //A, B, C, D, F quantities of people who get those grades
for(let i = 0; i < scoresArray.length; i++){
var sco = parseInt(scoresArray[i]);
if(sco >= 90){
result[0] += 1; //sum 1 person to the A place [0] == 1 position
}
else if(sco >= 80){
result[1] += 1; //sum 1 person to the B place [1] == 2 position
}
else if(sco >= 70){
result[2] += 1; //sum 1 person to the C place [2] == 3 position
}
else if(sco >= 60){
result[3] += 1; //sum 1 person to the D place [3] == 4 position
}
else
result[4] += 1; //sum 1 person to the F place [4] == 5 position
}
return result;
}
function setTableContent(userInput) {
var scores = parseScores(userInput); //parse scores from the user input
var arrayGrade = buildDistributionArray(scores); //creating the array of the quantity of people who get the letter grade
var getTable = document.getElementById('distributionTable'); //creating a variable table using the distributionTable id
var flag = 0; //flag in false
var i = 0;
while(i < arrayGrade.length){
if(arrayGrade[i] != 0){ //if the distincts locations of the array is not 0
flag = 1; //flag becomes true
}
i++;
}
if(flag == 1){ //if the flag is true
//create the table rows with the styles
getTable.innerHTML =`
<tr id="firstRow">
<td><div style="height:30px" class="bar0"></div></td>
<td><div style="height:20px" class="bar1"></div></td>
<td><div style="height:10px" class="bar2"></div></td>
<td><div style="height:0px" class="bar3"></div></td>
<td><div style="height:20px" class="bar4"></div></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>F</td>
</tr>
<tr>
<td class="grade"></td>
<td class="grade"></td>
<td class="grade"></td>
<td class="grade"></td>
<td class="grade"></td>
</tr>`;
var j = 0;
while(j < arrayGrade.length){
var barNames = document.getElementsByClassName("bar"+j); //bar0, bar1, bar2, bar3, bar4
document.getElementsByClassName("grade")[j].innerHTML = arrayGrade[j]; //grade0, grade1, grade2, grade3, grade4
barNames[0].style.height = (arrayGrade[j] * 10)+"px"; //3 * 10 == 30, 1 * 10 = 10; to create the graph height px
j++; //next number from 0 - 4
}
}
else{ //else no table to display
getTable.innerHTML = "<tr><td>No graph to display</td></tr>"; //Printing No Graph To Display
}
}
// The argument can be changed for testing purposes
// setTableContent("45 78 98 83 86 99 90 59 100 200 50 30 20 25 60 65 500 1000");
Help here
function bodyLoaded(input){
setTableContent(input);
}
function fn1(){
const str = document.getElementById('scores-input').value;
// alert("Value inside the text box is: "+str);
bodyLoaded(str);
}
you should add preventDefault to fn1 like this:
function fn1(e){
e.preventDefault();
const str = document.getElementById('scores-input').value;
// alert("Value inside the text box is: "+str);
bodyLoaded(str);
}

javascript calculation grand total result become double

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;
}
}
}

Colorizing table rows based on high/ low value with Javascript or Jquery

I am trying to create a function that will colorize the contents of the table based on the values of the row.
I am able to get the data from each row into an array and save the low and high values to a variable. How can I add a class low or high to the low and high values in each row?
In each tr I only want to compare the 1st,2nd,and 3rd position as the zero position is the index.
function showRows(s) {
var t = s.options[s.selectedIndex].text;
var rows = document.getElementById('mytab').getElementsByTagName('tr'),
i = 0,
r, c;
while (r = rows[i++]) {
if (t == 'All') {
r.style.display = ''
} else {
c = r.getElementsByTagName('td')[0].firstChild.nodeValue;
sxval = r.getElementsByTagName('td')[1].firstChild.nodeValue;
fcval = r.getElementsByTagName('td')[2].firstChild.nodeValue;
sgval = r.getElementsByTagName('td')[3].firstChild.nodeValue;
unval = r.getElementsByTagName('td')[4].firstChild.nodeValue;
array = [sxval, fcval, sgval, unval]
var low = Math.min(...array)
var high = Math.max(...array)
console.log("lowest" + " " + low)
console.log("highest" + " " + high)
console.log(c)
console.log(t)
r.style.display = parseInt(c) == parseInt(t) ? '' : 'none';
}
}
}
<body>
<table align="center" border="1" width="50%" cellspacing="0" cellpadding="4">
<tr>
<th>
<select name="mylist" onchange="showRows(this)">
<option value="m1">All</option>
<option value="m2">4</option>
<option value="m3">4.5</option>
<option value="m4">5</option>
</select>
</th>
</tr>
<br>
<table id="mytab" align="center" border="1" width="50%" cellspacing="0" cellpadding="4">
<tr class="content">
<td class="cj-has-text-centered contentcheck">
4 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
<tr class="content">
<td class="cj-has-text-centered contentcheck">
4.5 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
<tr class="content">
<td class="cj-has-text-centered contentcheck">
5 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
</table>
You can use Jquery to do this. Here is the sample. Hope to help, my friend :))
<style>
.highest{
background-color:blue;
}
.lowest{
background-color:red;
}
</style>
function showRows(s) {
var t = s.options[s.selectedIndex].text;
var rows = document.getElementById('mytab').getElementsByTagName('tr'),
i = 0,
r, c;
while (r = rows[i++]) {
if (t == 'All') {
r.style.display = ''
} else {
c = r.getElementsByTagName('td')[0].firstChild.nodeValue;
sxval = r.getElementsByTagName('td')[1].firstChild.nodeValue;
fcval = r.getElementsByTagName('td')[2].firstChild.nodeValue;
sgval = r.getElementsByTagName('td')[3].firstChild.nodeValue;
unval = r.getElementsByTagName('td')[4].firstChild.nodeValue;
array = [sxval, fcval, sgval, unval]
var low = Math.min(...array)
var high = Math.max(...array)
console.log("lowest" + " " + low)
console.log("highest" + " " + high)
console.log(c)
console.log(t)
r.style.display = parseInt(c) == parseInt(t) ? '' : 'none';
//Skip the first column, use :not(:first-child)
$('tr').each(function(){
var vals = $('td:not(:first-child)',this).map(function () {
return parseInt($(this).text(), 10) ? parseInt($(this).text(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
var max = Math.max.apply(Math, vals);
// tag any cell matching the min and max value
$('td', this).filter(function () {
return parseInt($(this).text(), 10) === min;
}).addClass('highest');
$('td', this).filter(function () {
return parseInt($(this).text(), 10) === max;
}).addClass('lowest');
});
}
}
};

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>

Categories