Forum Moderators: open
I am attempting to create a table, which will consist of four columns and an indefinitely number of rows, then use a javascript to calculate the difference between the second and third columns and display the result in the fourth column.
The first column will be the item name.
The second column will be its current numerical value (entered manually)
The third column will be its previous numerical value (entered manually)
The final column would be a calculation that subtracts the previous value from the current value, and assigns it the color RED if it's negative and GREEN if 0 or positive.
This would occur for each row individually. each row would have a previous value, current value, and the difference between the two, calculated dynamically & assigned a color.
Is this a fairly simple undertaking?
I apologize if anything was unclear here or if this is an involved question that would eat someone's time.
Thanks again to everyone who posts here - this is an awesome forum and hopefully I'll be knowledgeable enough to help people out soon.
Best Regards,
D
Keep track of the rows with a counter, then increment with every row you output:
num_rows++;
for (i=1;i<4;i++) {
var fieldname='field_' + num_rows + '_' + i;
// gives you field_2_3, for example
tablecontent += '<td><input type="text" name="'+fieldname+'"id="'+fieldname+'" value="0"></td>';
}
So you would then calculate with two nested loops, or just an inline calculation something to the effect of:
for (i=1;i<=num_rows;i++) {
var rowtotal=0;
var sec = 'field_'+i+'_2';
var third = 'field_'+i+'_3';
var st = 'field_'+i+'_4';
var subtot = document.getElementById(sec).value-document.getElementById(third).value;
document.getElementById(st).value=subtot;
page_total+=subtot;
}
document.getElementById('total').value=page_total;
The above is not working code and you'll encounter some issues - for example, you will probably get NaN (not a number) on your first try because text values often are interpreted as strings, and they need to be forced to be treated as numbers. There is also a floating point decimal issue that appears from time to time that makes you pull hair over the simplest math.
But this will get you started, and is only one of many possible approaches.