Javascript Looping With Sum Operation - javascript

I want to Loop a NAFAG field and sum every NAFAG field with a scheme like this. Every time I repeat the NAFAG sum, the result should be added to the KNAFA field
0 + -30000 results to the 2nd row KNAFA field
0 + -30000 + -30000 results to the 3rd row KNAFA field
0 + -30000 + -30000 + -30000 results to the 4th row KNAFA field
0 + -30000 + -30000 + -30000 + -30000 results to the 5th row KNAFA field
can anyone help me with this loop.

I hope my code help you.
HTML
<table>
<thead>
<th>KNAFA</th>
<th>NAFAG</th>
</thead>
<tbody>
</tbody>
</table>
Javascript
let nafag = [0, -3000, -3000,-3000,-3000,-3000, -3000];
let sum = 0;
for (const elem of nafag) {
sum += elem;
let elements = "<tr><td>" + sum + "</td><td>" + elem + "</td></tr>";
var parent_tbody = document.getElementsByTagName("tbody");
var new_tr = document.createElement('tr');
new_tr.innerHTML = elements;
parent_tbody[0].appendChild(new_tr);
}
Result
KNAFA
NAFAG
0
0
-3000
-3000
-6000
-3000
-9000
-3000
-12000
-3000
-15000
-3000
-18000
-3000

Related

How to check if number is up of multiplication table jquery/javascript

On my store, I want to offer a promotion for people who buy up to 1499, 2998, 4497, etc. (it is a multiplication of 1499);
do you recommend me use the conditional if? use switch? or what do you do in this case?
I ask you this be cause when they buy up to the values (1499,2998, etc) I need to show a div saying that the person won a promotion
I'm thinking do a multiplication of 1499 and check the total of the person is up to 1499,2998 etc, actually a make a multiplication table but I dunno how to check if is between a range
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");```
The table can be there just for display.
const num = 1499;
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");
To actually calculate the amount won from what the user has bought, divide the amount by 1499 and then call Math.floor on it:
const amountWon = input => Math.floor(input / 1499);
console.log(
amountWon(1498),
amountWon(1499),
amountWon(1500),
amountWon(2997),
amountWon(2998),
);
But make sure to do the calculation on the server-side as well, since none of the code you run on the client side can be trustworthy.

Creating Html table from array (Using prompt)

I am new to Html. This is my first html javascript program and I have an issue with it.
A user puts his/her gpa CS102 A 3, Math101 B 3. Then, I put the data into an Array. The problem is when I create the table. I want to create a table like
THL100 B+ 3
PHL107 A 3
ENG120 C+ 3
MTH245 A 4
CSC221 A 3
What kind of loop I should use? I tried to use a for loop but it just doesn't work.
Here is my code:
function load(){
var data = [];
while(true) {
line = prompt("Enter course name, grade, and credit hours or click OK with no data to terminate");
if(line == null || line == "") {
break;
}
var values = line.split(/\s/);
var citem = values[0];
data.push(citem);
var gpa = parseFloat(values[1]);
var cgpa = [gpa];
data.push(cgpa);
var unit = values[2];
var cunit = [unit];
data.push(cunit);
}
return data;
}
function display(data) {
var table=document.getElementById('result');
table.innerHTML= "<tr><th> COURSE </th><th> GRADE </th><th> HOURS </th></tr>";
for(var i in data){
table.innerHTML +="<tr><td>" + data[i] + "</td><td>" + data[i]+1 + "</td><td>" + data[i]+2 + "</td></tr>";
}
}
data = load();
display(data);
<table id="result" border="1px" class="classy">
</table>
<span id="text"></span>
the problem is with accessing data not the loop, store each line as one element in the array, like object will be easy:
function load(){
var data = [];
while(true) {
line = prompt("Enter course name, grade, and credit hours or click OK with no data to terminate");
if(line == null || line == "") {
break;
}
var values = line.split(/\s/);
var line = {
COURSE: values[0],
GRADE: parseFloat(values[1]),
HOURS: values[2]
};
data.push(line); // now your array is [{COURSE: value, GRADE: value, HOURS: value}, {}, ...]
}
return data;
}
function display(data) {
var table=document.getElementById('result');
table.innerHTML= "<tr><th> COURSE </th><th> GRADE </th><th> HOURS </th> </tr>";
for(var i in data){
table.innerHTML +="<tr><td>" + data[i]["COURSE"] + "</td><td>" + data[i]["GRADE"] + "</td> <td>" + data[i]["HOURS"] + "</td></tr>";
}
}
UPDATE: yes the data is accessible inside the loop but for any variable
function display(data) {
var table = document.getElementById('result');
table.innerHTML = "<tr><th> COURSE </th><th> GRADE </th><th> HOURS </th> </tr>";
let totalgp = 0; // if the total is for all courses define it here
for (var i in data) {
let totalgp = 0; // if total grade for each course separately define it inside the loop
if (data[i]["GRADE"] == "A") {
var gp = 4 * data[i]["HOURS"];
totalgp = totalgp + gp;
}
table.innerHTML += "<tr><td>" + data[i]["COURSE"] + "</td><td>" + data[i]["GRADE"] + "</td> <td>" + data[i]["HOURS"] + "</td></tr>";
}
}
The data should be stored in a 2-dimensional array to easily access the elements. The usage of for loop is right.
To append the first row -
table.innerHTML +="<tr><td>" + data[0][0] + "</td><td>" + data[0][1] + "</td> <td>" + data[0][2] + "</td></tr>";
similarly for 2nd row,
table.innerHTML +="<tr><td>" + data[1][0] + "</td><td>" + data[1][1] + "</td> <td>" + data[1][2] + "</td></tr>";

Not a Number (NaN) - Javascript

I have a function to add up my sum and charge respectively. But when i alert sum + charge, i get NaN. why is this happening?
<script>
sum = 0;
charge = 0;
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<table style="width:100%;" class="table" id="tables">'+
'<td class="name" >'+std.name+'</td>'+
'<td><p class="total" ><span class="min-total" name="total" id="total"></span></p></td>'+
'</table>'+
'</div>'
$('.panel').on('keyup','.quantity',function()
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".min-total span").text(quantity * price);
sum = 0;
$(".sum-total").each(function(){
sum = sum + Number($(this).text());
})
}
$('.charge').on('keyup','.charge',function(){
$('.charge span').text( Number($(this).val()));
charge = Number($(this).val());
alert(sum + charge);
</script>
The wikipedia definition says:
In computing, NaN, standing for not a number, is a numeric data type
value representing an undefined or unrepresentable value. https://en.wikipedia.org/wiki/NaN
In your code either $(this).text() or $(this).val() cannot be computed by Number() and return NaN. Make sure the value of those is either a Number or a string made of numbers.

How to display value of row and column for html table

I created Html table using JavaScript. Its working perfectly, its giving me row and column perfectly. But I want to display the cell value
Javscript Code
var table ="";
var row = 2;
var cols = 2;
//var row =2,cols =4;
for(var r=0; r<row;r++)
{
table+='<tr>'; // open row
for (var c=1; c<=cols;c++)
{
table += "<td>"+ c+'</td>';
}
table+= "</tr>"; // close row
}
document.write("<table>"+ table + "</table>");
output
1 2
1 2
Wanted output. cell 2,1 would have "(2,1)" in it
1,1 2,1
1,2 2,2
What am I missing ? I try to give the for loop value but no success.
You can use table += <td>" + r + "," + c +'</td>

JavaScript & HTML - Modifying dynamically created subclasses within a dynamically created class

Problem:
I have a dynamically created HTML table, that is used for filling out time sheets. It is created programmatically - there is no formal control. The design is a mix of CSS with text boxes being created through JavaScript. Now each 'row' of this table is in a class called 'divRow', and is separated from the others by having 'r' and the number of the row assigned to it as the class (i.e 'divRow r1', 'divRow r2', etc.).
Within each of these 'divRow's, I have cells in a class called 'divCell cc'. These do not have any identifiers in the class name. At the very last cell, I have a 'Total' column, which ideally calculates the total of the row and then adds it into a dynamically created text box.
What I have at the moment:
// Function to create textboxes on each of the table cells.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
//var getRow = $(this).parent().attr('class'); - this gets the 'divRow r#' that it is currently on.
var arr = document.getElementsByClassName('cc');
var tot = 0;
for(var i = 0; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
$('#t' + c.id).focus();
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});
As you can see, when the user clicks on the 'divCell cc', it creates a text box if one is not present. If the user clicks on the 17th column ('x17'), then it runs the for loop, and assigns the value of the total to the text box.
What I need to happen:
So what happens now is that the last cell sums the total of each cell that has a value. However, they are not row-dependent. I need it to calculate based on the row that it is currently 'on'. So if I'm calculating the 2nd row, I don't want the sum of the first, second and third being entered into the total, I just want the 2nd rows' values summed.
What I've tried:
I've tried looping through and using the 'divRow r#' number to try and get the items in the array that end in that number. (cells are given an id of 'x#y#' and the text boxes assigned to those cells are given an id of 'tx#y#').
I've tried getting elements by the cell class name, and then getting their parent class and sorting by that; didn't get far though, keep running into simple errors.
Let me know if you need more explanation.
Cheers,
Dee.
For anyone else that ever runs into this issue. I got it. I put the elements by the row class into an array, and then using that array, I got the childNodes from the row class. The reason the variable 'i' starts at 2 and not 0 is because I have 2 fields that are not counted in the TimeSheet table (Jobcode and description). It's working great now.
Cheers.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
// Get current row that has focus
var getRow = $(this).parent().attr('class');
// Get the row number for passing through to the next statement
var rowPos = getRow.split('r', 5)[1];
// Get all the elements of the row class and assign them to the rowClass array
var rowClass = document.getElementsByClassName('r' + rowPos)
// Given the rowClass, get the children of the row class and assign them to the new array.
var arr = rowClass.item(0).childNodes
// Initialize the 'total' variable, and give it a value of 0
var tot = 0;
// Begin for loop, give 'i' the value of 2 so it starts from the 3rd index (avoid the Req Code and Description part of the table).
for(var i = 2; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
// Assign focus to the 'Total' cell
$('#t' + c.id).focus();
// Assign the 'total' variable to the textbox that is dynamically created on the click.
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});

Categories