Getting the sum and average in javascript - javascript

How to get the sum and average of the last column.In my code it wont get the correct value if the table has one,two and three rows.This works only on table with 4 rows.I know something wrong with my code but i cant figure it out how the loop works within .each function.
Important note:this runs with keyup event to update table data.Its not just a display.To be exact it is an update form.
Desired output
Item | value1 | value 2 | value3 |value 4 | Average
01 90 88 87 80 82.25
Total average 82.25 result of 82.25/1 number of row
if two rows
Item | value1 | value 2 | value3 |value 4 | Average
01 90 88 87 80 82.25
02 80 85 86 84 83.75
Total average 83 result of (82.25+83.75)/2 number of rows
But the result comes out with multiple loops
Here is the console.log(totalAverage)
86.25
176
264.75
353.5
442.25
86.25
176
264.75
353.5
442.25
Problem:How to suppress or skip this unnecessary values.I only need the 86.25 to display in total-ave.Note: this is only single row right now and have already incountered this miscaculation, how much more if the table has multiple rows then?
Html
<tr>
<th colspan="12"><h4>Card</h4></th>
</tr>
<tr>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
<th>Average</th>
</tr>
</thead>
<tbody>
#foreach($update_card['AllGrade'] as $subject)
{!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<th colspan="3">{!! $subject->subject !!}</th>
<td colspan="2">{!! Form::text('term_1[]',$subject->term_1,['class'=>'form-control','name[]'=>'term_1','id[]'=>'term_1','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_2[]',$subject->term_2,['class'=>'form-control','name[]'=>'term_2','id[]'=>'term_2','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_3[]',$subject->term_3,['class'=>'form-control','name[]'=>'term_3','id[]'=>'term_4','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name[]'=>'term_4','id[]'=>'term_4','value'=>'0']) !!}</td>
<td colspan="2" class="average" id="average" value="0"> Average</td>
</tr>
#endforeach
<tr>
<th colspan="11">Total Average:</th>
<th>{!! Form::text('scholar_GPA',$update_card->scholar_GPA,['class'=>'form-control total-ave','name' => 'total-ave','id' => 'total-ave','value' => '0']) !!}</th>
</tr>
Javascript snippet
$("input").on("keyup", function(){
$("tbody tr").each(function() {
var col=1;
var tr =1;
var t = 0;
var a = 0;
$(this).children('td').not(':last').each(function () {
var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
// console.log(number);
// console.log(col);
t += parseInt(number);
// console.log(t);
a = t/col;
col++;
});
$(this).children('td').last().html(a);//last td of the row
// console.log(a);
col=1;
tr++;
});
calcTotalave();
});
// calculate total average
function calcTotalave() {
var totalAve = 0;
var tot=0;
var c = 2;
var count =0;
$( ".average" ).each(function() {
// console.log($(this).html());
var thisAve = parseFloat($(this).html());
if(!thisAve || thisAve === NaN || thisAve == "") {
thisAve = 0;
}
totalAve += thisAve;
//alert('count'+thisAve+totalAve);
console.log(totalAve);
count++;
});
c++;
totalAve = totalAve/c;
// console.log(totalAve);
$("#total-ave").val(totalAve);
}

UPDATED: fiddle below with comments, press space-bar to run, based around the below function.
the fiddle is made to cycle through and calc cells by row, so no .average class required. You will need to adapt it for your html table layouts as per your database output.
calcTotalave();
});
// calculate total average
function calcTotalave() {
var totalAve = 0;
$( ".average" ).each(function() {
var thisAve = parseFloat($(this).text()) || 0; // always return a number
totalAve += thisAve;
});
var Aver = totalAve / $('.average').length;
console.log(totalAve);
$("#total-ave").text(Aver);
}
instead of classing each cell as .average you could use the selector to target all the cells td of a given row:
$('input').change(function() {
calTotalAverages(); // the magic and collect the total average
});
function calTotalAverages(){
var SumAve = 0, nums = 0; // to collect total averages and the number of rows
$('tr').each(function(i) {
if (i > 0) { // ignore the first row
var $this = $(this);
SumAve += calcRowAve($this); // add up the returned averages and run the function
nums ++; // count the rows
}
}); // cycle through each row
var sum = (SumAve / nums);
$('#total-ave').text(sum.toFixed(2)); // display the total average
return sum; // return the total average
}
// calculate total average
function calcRowAve(targetRow) {
var totalAve = 0,
targetCells = targetRow.children(),
targLength = targetCells.length - 2; // total number of values in a row
targetCells.each(function(i) {
if (i > 0 && i <= targLength) {
var thisAve = parseFloat($('input',this).val()) || parseFloat($(this).text()) || 0; // always return a number
totalAve += thisAve;
} // check to ignore the first cell and the last
});
var Aver = totalAve / targLength; // get the average
targetCells.last().text(Aver); // update the last cell of the row
return Aver; // return the average for this row
}
#total-ave {
position: fixed;
right: 2em;
top: 8em;
}
input{
width: 5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>item 1</th>
<th>value 1</th>
<th>value 2</th>
<th>value 3</th>
<th>value 4</th>
<th>average</th>
</tr>
<tr>
<td>1</td>
<td>90</td>
<td>88</td>
<td>87</td>
<td>80</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>80</td>
<td>85</td>
<td>86</td>
<td>84</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td><input type='number'></td>
<td><input type='number'></td>
<td><input type='number'></td>
<td><input type='number'></td>
<td></td>
</tr>
</table>
<div id='total-ave'></div>

Related

jQuery - Combine <TR>(s) values that are in same Section # with same Group # / remove duplicates

I have updated the code, which is currently working up to the Place for each Group #. The existing code determines a matching Section # with Group #, and combines the TR values, adding the Average(s) and dividing by the number of TR(s), and removing any duplicate(s).
I am attempting to determine a Place for each Group # within a Section #. (*example - Section 1: Group #1 - 1st / Group #2 - 3rd / Group #3 - 2nd)
$(function() {
alert('View Table Before Grouping');
sort_array();
combine_rows();
compute_average();
});
//function sort_array
function sort_array() {
var $table = $('table');
var header = $('table tr:first-child').html();
var l = [];
$table.find('tr').each( function() {
//get values from td(s) from each row
var section = $(this).find('.class_section_number').text();
var group_number = $(this).find('.group_number').text();
var average = $(this).find('td:eq(2)').text();
var place = $(this).find('td:eq(3)').text();
//add to array
l.push([section, group_number, average, place]);
//remove saved row
$(this).remove();
});
l = l.slice(1);
//sort the array by section #, then group #
l.sortBy(0, true, 1, true, 2, false);
$table.prepend(header);
//rebuild table after sort
$.each(l, function(key, value) {
$('table').append('<tr><td class="class_section_number">' + value[0] + '</td><td class="group_number">' + value[1] + '</td><td class="grade">' + value[2] + '</td><td>' + value[3] + '</td></tr>');
});
}
//function combine_rows
function combine_rows() {
$('table tr').each( function() {
//get current row data
var section = $(this).find('.class_section_number').text();
var group = $(this).find('.group_number').text();
var average = $(this).find('td:eq(2)').text();
//get next row data
var next_section = $(this).next('tr').find('.class_section_number').text();
var next_group = $(this).next('tr').find('.group_number').text();
var next_average = $(this).next('tr').find('td:eq(2)').text();
//check for section # / group # row match
if ((section === next_section) && (group === next_group)) {
//check for empty average
if (average === 'No Data') {
average = 0 + ',' + next_average;
}
else {
average = average + ',' + next_average;
}
//set combined average
$(this).next('tr').find('td:eq(2)').text(average);
//remove matching row
$(this).remove();
}
});
}
//function compute_average
function compute_average() {
$('table tr').each( function() {
//get average from row
var average = $(this).find('td:eq(2)').text();
//split average into array (*if comma separated values)
average_array = average.split(',');
var total = 0;
//total average values from array / divide by count and set
for (var i = 0; i < average_array.length; i++) {
total += (+average_array[i]);
$(this).find('td:eq(2)').text((total / average_array.length).toFixed(2));
}
});
}
//array sort function
Array.prototype.sortBy = function (propertyName, sortDirection) {
var sortArguments = arguments;
this.sort(function (objA, objB) {
var result = 0;
for (var argIndex = 0; argIndex < sortArguments.length && result === 0; argIndex += 2) {
var propertyName = sortArguments[argIndex];
result = (objA[propertyName] < objB[propertyName]) ? -1 : (objA[propertyName] > objB[propertyName]) ? 1 : 0;
result *= sortArguments[argIndex + 1] ? 1 : -1;
}
return result;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Section #</th>
<th>Group #</th>
<th>Averages</th>
<th>Place</th>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td class="grade">78.29</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td class="grade">85.52</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">1</td>
<td class="grade">74.41</td>
<td>Test Place 2nd</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td>No Data</td>
<td>Test Place 3rd</td>
</tr>
<tr><td class="class_section_number">2</td>
<td class="group_number">1</td>
<td class="grade">78.90</td>
<td>Test Place 2nd</td>
</tr>
</tr>
<tr><td class="class_section_number">1</td>
<td class="group_number">3</td>
<td class="grade">91.03</td>
<td>Test Place 2nd</td>
</tr>
</tr>
<tr><td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">81.69</td>
<td>Test Place 2nd</td>
</tr>
<tr>
<td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">81.13</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">78.13</td>
<td>Test Place 1st</td>
</tr>
</tbody>
</table>

Calculate sum of merged rows and display in third column

I am trying to calculate the monthly expenses from my table.
Want to sum up all the amount month wise and display in total like for January month total will be $180, March will be $230 and May $200. The amount should reflect in the total column. I have created this table using ng-repeat of angular framework (dynamic table)
JSFIDDLE
I have tried below code which will sum up all the individual cols having only numeric values. This code is not working for merged rows.
for (col = 1; col < ncol + 1; col++) {
console.log("column: " + col);
sum = 0;
$("tr").each(function(rowindex) {
$(this).find("td:nth-child(" + col + ")").each(function(rowindex) {
newval = $(this).find("input").val();
console.log(newval);
if (isNaN(newval)) {
$(this).html(sum);
} else {
sum += parseInt(newval);
}
});
});
}
});
Any help on this will be really helpful.
I would add a data-month attribute to the cell displaying the amount, it is not visible to users, but super helpful for you. Have a look at the solution below.
function getMonth(month) {
var monthCells = $("td[data-month='" + month + "']"); // get all TDs with a data month attribute
var sum = 0;
for(var i = 0; i < monthCells.length; i++){ // iterate over the tds
var amountCell = monthCells[i]; // get a td for given iteration
var amountCellText = $(amountCell).text(); // get the text content
sum += parseInt(amountCellText.replace(/\D/, "")); // in amoutnCellText replace anything that's not a digit into an empty string
}
return sum;
}
console.log(getMonth("march"))
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr>
<td rowspan="2">January</td>
<td data-month="january">$100</td>
</tr>
<tr>
<td data-month="january">$80</td>
</tr>
<tr>
<td rowspan="2">March</td>
<td data-month="march">$200</td>
</tr>
<tr>
<td data-month="march">$30</td>
</tr>
<tr>
<td>May</td>
<td data-month="may">$200</td>
</tr>
</table>
How about something like this?
vm.data = [
{
month: 'January',
savings: [
{ amount: 100 },
{ amount: 200}
]
},
{
month: 'February',
savings: [
{ amount: 300 },
{ amount: 400 }
]
}
];
In html:
<table class="table table-bordered table-condensed">
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr ng-repeat="row in vm.data">
<td>{{row.month}}</td>
<td>
<table class="table table-bordered table-condensed">
<tr ng-repeat="s in row.savings">
<td>${{s.amount}}</td>
</tr>
</table>
</td>
<td>${{vm.getTotal(row.savings)}}</td>
</tr>
</table>
In JS:
vm.getTotal = getTotal;
function getTotal(savings) {
var total = 0;
angular.forEach(savings,
function (row) {
total += row.amount;
});
return total;
}
The key here is data modeling so that you have a simple function in getting total. Hope it will help.
Sample

get the sum of 2nd column in html table

input : <table> <tr> <td>100</td> </tr> <tr> <td>200</td> </tr> </table> from the input it should return me the sum=300 instead I'm getting the output as 100200
function Save_Name()
{
var Invoice = $("#text_invoice").val();
var Name = $("#text_name").val();
var Date = $("#text_date").val();
var Amount = 0;
var n = $("table").find("tr").length;
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#table1").find("tr").eq(i).find("td").eq(2).text();
Amount += parseFloat(Amt);
}
}
}
eq starts with 0 index.The output 100200 is because it is concatenating the string instead of adding the values.Also use parseInt to convert the number from string to integer.
function Save_Name() {
var Amount = 0;
// will get all tr
var n = $("#table1 tr");
n.each(function(i, v) {
// table have only one td per tr so eq(0) will give first td
// trim is used to remove any white space
Amount += parseInt($(v).eq(0).text().trim(), 10)
})
console.log(Amount)
}
Save_Name()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
Here's another way to do the same thing. Basically, I use map to create a map of integer values, then I use "get" to convert them into an array, and finally I use reduce to calculate the sum of the values in the array.
P.S.: To calculate the second column, all you need to do is to use nth-child(2) instead of nth-child(1).
$(function(){
var sum = $('#table1 tr td:nth-child(1)').map(function() {
return parseInt($(this).html(), 10)
}).get().reduce(function(a, v){
return a + v;
}, 0);
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="table1">
<tr>
<td>100</td>
</tr>
<tr>
<td>200</td>
</tr>
</table>
I have alert the value of sum Amount and it is equal to 300 .
You were doing some mistake as eq(2) instead of eq(0)
But Here's the working snippet:
function Save_Name()
{
var Amount = 0;
var n = $('#test tr').length;
// alert(n);
if (n - 1 > 0)
{
for (var i = 0 ; i < n; i++)
{
var Amt = $("#test").find("tr").eq(i).find("td").eq(0).text();
Amount += parseFloat(Amt);
}
alert(Amount);
}
}
Save_Name();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='test'>
<tr> <td>100 </td></tr>
<tr> <td>200 </td></tr>
</table>

Multiple times of input in the same text field with javascript

In this code i can only input ones. If ever there are any changes of any row of column Term4, the value of the Ave is blank. How to make it dynamic? I need help here because all my codes were only searched piece by piece until i came up with this script. I'm stuck here for days. Any help would be a blessing. This is my first input...
Sample table, output 1:
Subject | Term1 | Term2 | Term3 | Term4 | Ave
Math 81 87 81 80 82.4
Science 89 83 81 80 83.25
If i change the input in term 4, the ave column will be blank.
Sample table output 2:
Subject | Term1 | Term2 | Term3 | Term4 | Ave
Math 81 87 81 85
Science 89 83 81 80 83.25
HTML:
<tr>
<th colspan="3">Learning Areas</th>
<th colspan="2">Term 1</th>
<th colspan="2">Term 2</th>
<th colspan="2">Term 3</th>
<th colspan="2">Term 4</th>
<th>Ave</th>
</tr>
</thead>
<tbody>
#foreach($card['AllGrade'] as $subject)
{!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<td colspan="3">{!! $subject->subject !!}</td>
<td colspan="2">{!! $subject->term_1 !!}</td>
<td colspan="2">{!! $subject->term_2 !!}</td>
<td colspan="2">{!! $subject->term_3 !!}</td>
<td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name'=>'term_4','id'=>'term_4','value'=>'']) !!}</td>
<td colspan="2" class="aver" name ="ave" id ="ave" value=""> total</td>
</tr>
#endforeach
//javascript
<script type="text/javascript">
$("tbody tr").each(function() {
var total = 0;
var ave = 0;
var count = 1;
$(this).children('td').not(':first').not(':last').each(function () {
//"this" is the current element in the loop
var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
total += parseInt(number);
ave = total/count;
count++;
});
if('.form-control'){
$(this).on('keyup', 'td:eq( 4 ) input', function(){
$('.form-control').on("input", function() {
var dInput = this.value;
total += parseInt(dInput);
ave = total/count-1;
});
console.log(ave);
$(this).parent().next().html(ave);
});
}
$(this).children('td').last().html(ave);
To avoid that NaN issue, I made sure that changed input is taken as 0. And then recalculated average, then it works.
$("tbody tr").each(function() {
var total = 0;
var ave = 0;
var count = 1;
$(this).children('td').not(':first').not(':last').each(function () {
//"this" is the current element in the loop
var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
total += parseInt(number);
ave = total/count;
count++;
});
$(this).children('td').last().html(ave);
if('.form-control'){
$(this).on('keyup', 'td:eq( 4 ) input', function(){
$('.form-control').on("input", function() {
var dInput = parseInt(this.value);
if(!dInput || dInput === NaN) {
dInput = 0;
}
var total = 0;
var count = 1;
$(this).parent().siblings().not(':first').not(':last').each(function () {
//"this" is the current element in the loop
var number = $(this).html();
total += parseInt(number);
count++;
});
total += dInput;
console.log(total);
console.log(count);
var ave = total/count;
//console.log(ave);
$(this).parent().siblings(":last").html(ave);
calcTotalave();
});
});
}
});
calcTotalave();
// calculate total average
function calcTotalave() {
var totalAve = 0;
$( ".aver" ).each(function() {
console.log($(this).html());
var thisAve = parseFloat($(this).html());
if(!thisAve || thisAve === NaN) {
thisAve = 0;
}
totalAve += thisAve;
});
console.log(totalAve);
$("#total-ave").val(totalAve);
}

Stripe table JavaScript

I am trying to make a table which will display colours for odd and even table rows, not sure where I'm going wrong
HTML:
<table id="tableStyles" border="1">
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Even</td>
<td>Even</td>
<td>Even</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
</table>
JS:
var isEven = function(someNumber) {
return (someNumber%2 == 0) ? true : false;
};
if isEven = true {
var styletab = document.getElementsByTagName("tableStyles");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < styletab.length; i++) {
styletab[i].style.fontSize = "12px";
styletab[i].style.color = "blue";
}
} else {
var styletab = document.getElementsByTagName("tableStyles");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < styletab.length; i++) {
styletab[i].style.fontSize = "12px";
styletab[i].style.color = "red";
}
}
I'd suggest:
Array.prototype.forEach.call(document.querySelectorAll('#tableStyles tr'), function (tr) {
tr.classList.add((tr.rowIndex%2 === 0 ? 'even' : 'odd'));
});
This presumes you have styles set, in CSS, for tr.odd and tr.even; also that you're using a relatively up-to-date browser; Internet Explorer 8+ for document.querySelectorAll(), and Internet Explorer 9+ for Array.prototype.forEach().
Array.prototype.forEach.call(document.querySelectorAll('#tableStyles tr'), function(tr) {
// rowIndex is the index of the current <tr> in the table element:
tr.classList.add((tr.rowIndex % 2 === 0 ? 'even' : 'odd'));
});
.even {
color: red;
}
.odd {
color: blue;
}
<table id="tableStyles" border="1">
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Even</td>
<td>Even</td>
<td>Even</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
</table>
Alternatively, if you wanted to stripe only those elements selected (without reference to the rowIndex):
Array.prototype.forEach.call(document.querySelectorAll('#tableStyles tbody tr'), function(tr, collectionIndex) {
// collectionIndex (regardless of name, it's the second argument) is
// the index of the current array-element in the array/collection:
tr.classList.add((collectionIndex % 2 === 0 ? 'even' : 'odd'));
});
Array.prototype.forEach.call(document.querySelectorAll('#tableStyles tbody tr'), function(tr, collectionIndex) {
tr.classList.add((collectionIndex % 2 === 0 ? 'even' : 'odd'));
});
.even {
color: red;
}
.odd {
color: blue;
}
<table id="tableStyles" border="1">
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Even</td>
<td>Even</td>
<td>Even</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
<tr>
<td>Odd</td>
<td>Odd</td>
<td>Odd</td>
</tr>
</tbody>
</table>
From the code I can see that you are new to JS. So I think it is good to point out where you are going wrong, than fixing the whole thing for you.
//Here you are creating a function to return true or false using a function which
//already returning true or false.
var isEven = function(someNumber) {
return (someNumber%2 == 0) ? true : false;
};
//above can be reduced to this.
(someNumber%2==0); //will return true if even and false if odd.
// The syntax of if statement is wrong. It should be if (statement) { do stuff here...}
// Notice the difference between '=' and '=='. The first assigns value and the second checks if both sides are same.
// The isEven function should have an input to give either true or false.
// Finally you should first get the rows in the table as an array and loop through it and then do this if statement.
if isEven = true {
var styletab = document.getElementsByTagName("tableStyles");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < styletab.length; i++) {
styletab[i].style.fontSize = "12px";
styletab[i].style.color = "blue";
}
} else {
var styletab = document.getElementsByTagName("tableStyles");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < styletab.length; i++) {
styletab[i].style.fontSize = "12px";
styletab[i].style.color = "red";
}
}
// the above should be organised in the format below.
var table = ;//get the table here.
var rows = ;//get the rows in the table here.
for (i in rows) {
var row = rows[i]; //get the current row
var cells = ;//get cells from the current row
if(i%2==0) {
//set formatting for the cells here if the row number is even.
} else {
//set formatting for the cells here if the row number is odd.
}
}
Make sure you are absolutely sure of how the selectors (getElementById etc) work and what do they return so that you can use them correctly. for example getElementsByTagName searches based on the tag name ('div' 'table' etc) but getElementById searches by the id of the tags - 'tableStyles' in this case. Hope I pointed you in the right direction.
Final Correct answer provided by Balamurugan Soundarara
//Here we are searching for the document for element with the id 'tableStyles'. This returns only one DOM element.
var table = document.getElementById("tableStyles");
//Here we are searching the table element for all elements of the tag 'tbody'. This returns an array of elements. Here there is only one so we just use the first one (hence the [0] at the end)
var body = table.getElementsByTagName("tbody")[0];
//Here we are searching the body element for all elements of the tag 'tr'. This returns an array of row elements.
var rows = body.getElementsByTagName("tr");
//Here we are looping through the elements in the rows array.
for (var i=0 ; i<rows.length; i++) {
//Here we select the nth row in the array based on the loop index.
var row = rows[i];
//Here we are searching the row element for all elements of the tag 'td'. This returns an array of cells in the row.
var cells = row.getElementsByTagName("td");
//We are looping through all the cells in the array.
for(var j=0; j<cells.length; j++) {
//set the fontsize
cells[j].style.fontSize = "12px";
//check if the row is even. see how we dont need the isEven function. you can directly use the == function with the modulo operator.
if( i%2==0 ) {
//if it is even then the color is set to blue
cells[j].style.color = "blue";
} else {
//if it is even then the color is set to blue
cells[j].style.color = "red";
}
}
}
http://jsfiddle.net/ar5suz2g/4/

Categories

Resources