Changing value of input range not updating content on mobile - javascript

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

Related

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

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

Calculator HTML form using Javascript

i have a little issue. That's my code and i don't know what i have made wrong. I try to complete a simple HTML form to calculate a given number in a text input html element.
function rebate(){
var rebate_a,rebate_b,total,final;
var a = document.myform.rebatenum.value;
if( a <= 3000 )
{
final = a;
}
else if ( (a > 3000) && (a <= 10000 ) )
{
rebate_a = (a-3000) * 0.02;
total = rebate_a;
final = a - rebate_a;
}
else if ( (a > 10000) && (a <= 30000 ) )
{
rebate_a = (7000 * 0.02) + (a-10000) * 0.03;
total = rebate_a;
final = a - rebate_a;
}
else if ( (a > 30000) && (a <= 40000 ) )
{
rebate_a = (7000 * 0.02) + (20000 * 0.03) + (a-30000) * 0.05;
total = rebate_a;
final = a - rebate_a;
}
else if( (a >= 40000) && (a < 50000 ))
{
rebate_a = (7000 * 0.02) + (20000 * 0.03) + (10000 * 0.05) + (a-40000) * 0.06;
rebate_b = 25;
total = rebate_a + rebate_b;
final = a - total;
}
else
{
document.myform.final.value = "20";
}
document.getElementById("demo").innerHTML = a;
document.myform.final.value = final;
}
<form name="myform">
<table border="0">
<tr>
<td>Initial Price</td>
<td><input name="rebatenum" type="text" size="12" onchange="rebate();"></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Υπολογισμός" onclick="rebate();"></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Final Price after rebate:</td>
<td><input type="text" name="final" size="12"></td>
</tr>
</table>
</form>
<p id="demo"></p>
You can find it also here!!!
http://jsfiddle.net/pf7Lysqt/3/

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