Proper rows not getting colored - javascript

My rows are not getting colored properly"
Please have a look at my HTML output:
<table id="mytable" cellspacing="0" cellpadding="5">
<tbody>
<tr class="tableheader">
<th>Name</th>
<th>Code</th>
<th>Value</th>
<th>Bid</th>
<th>Offer</th>
</tr>
<tr class="rowoddcolor">
<td>Apple</td>
<td>APPL</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
<tr class="tablecontent">
<td>Microsoft</td>
<td>MSFT</td>
<td>78</td>
<td>70</td>
<td>75</td>
</tr>
<tr class="rowevencolor">
<td>Google</td>
<td>GOGL</td>
<td>101</td>
<td>98</td>
<td>102</td>
</tr>
<tr class="tablecontent">
<td>Nokia</td>
<td>NOK</td>
<td>10</td>
<td>8</td>
<td>9</td>
</tr>
<tr class="rowoddcolor">
<td>Samsung</td>
<td>SAMS</td>
<td>89</td>
<td>86</td>
<td>90</td>
</tr>
<tr class="tablecontent">
<td>IntelCorporation</td>
<td>INTC</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
</tbody>
</table>
Now only the 1st and 5th row getting colored? why not 3rd row?
updated code:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementsByClassName('tablecontent');
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
});
});
I am creating html through jquery consuming json. Table is getting created properly. Now through javascript, i am styling my alternate rows to different color and header should be in different color. This is my first question. Please see below my script:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementById("tablecontent");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr id="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
});
$(function(){
tablerows('mytable');
});
});
But my rows are not getting styled. Please tell me where is the problem.
Below is css code as well:
.rowoddcolor{
background-color:#FFFFFF;
}
.rowevencolor{
background-color:#D3D3D3;
}

I believe the function "tablerows" is getting executed before the build of table. So put that code after the append method.
Example :
$(document).ready(function() {
$.getJSON('table.json',function(data){
// existing stuff
$('#mytable').append(html);
tablerows('mytable');
});
});
Also the easiest way add the color class on alternating would be :
$('#mytable tr:even').addClass("rowevencolor");
$('#mytable tr:odd').addClass("rowoddcolor");

A few things:
First, Element ID's should be unique. Do not give every tr the same id tablecontent.
After that's fixed, you can ditch the entire helper function tablerows() as it is redundant and that logic can be moved to where you are building the table, i.e.:
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent row' + (i % 2 ? 'even' : 'odd') + 'color"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+ data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
Or simply use psuedo-selectors in your CSS as recommended by Kundan

The reason why your code is not highlighting table row #3 is because the result of getElementsByClassName is a NodeList, not an Array.
You will thus need to convert the NodeList to an Array before using the indexing operator for random access.
e.g.
var rowsList = tableid.getElementsByClassName('tablecontent');
var rows = Array.prototype.slice.call(rowsList);
for (i = 0; i < rows.length; i++)
// ...
Here is a working fiddle
However, as per Kundan's answer, it seems strange why you wouldn't use a jQuery solution, as it is much less work. jQuery fiddle here

Related

How to get text value of specific columns in a table for each row?

I have a simple HTML table that can contain 2-5 rows and 6 columns each. How can I get the value of 1 and 2 columns for each row? I would also like to display it in a output like this: Column1 Column2, Column1 Column2, Column1 Column2 would be the output if it has 3 rows.
EDIT: Created a jsfiddle to describe what Im trying to do and also the sample code where I am at so far https://jsfiddle.net/y6eoc0b4/
You can do this
var myTable = document.getElementById("myTable");
var rows = myTable.getElementsByTagName("tr");
console.log(rows);
var output = [];
for(var i = 0; i< rows.length; i++){
var cells = rows[i].getElementsByTagName("td");
output.push(cells[0].innerText+" "+cells[1].innerText)
}
document.getElementsByClassName("output")[0].innerText = output;
https://jsfiddle.net/LyswLtf8/
JSfiddle based on your comment here
//step first: select items like this
var fisrstTdArr = document.querySelectorAll(".location table tbody tr td:first-child");
var secondTdArr = document.querySelectorAll(".location table tbody tr td:nth-child(2)");
// or like this
var fisrstTdArr2 = document.querySelectorAll("#myId tbody tr td:first-child");
var secondTdArr2 = document.querySelectorAll("#myId tbody tr td:nth-child(2)");
// or even shorter if you have only one table on the page
var fisrstTdArr3 = document.querySelectorAll("td:first-child");
var secondTdArr3 = document.querySelectorAll("td:nth-child(2)");
for (var i = 0; i<fisrstTdArr.length; i++) { // than loop
console.log ('select method 1, fisrts column: ' + fisrstTdArr[i].innerText); // and use
console.log ('select method 1, second column: ' + secondTdArr[i].innerText);
console.log ('select method 2, fisrts column: ' + fisrstTdArr2[i].innerText);
console.log ('select method 2, second column: ' + secondTdArr2[i].innerText);
console.log ('select method 3, fisrts column: ' + fisrstTdArr3[i].innerText);
console.log ('select method 3, second column: ' + secondTdArr3[i].innerText);
}
<div class='location'>
<table id="myId">
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
</tbody>
</table>
</div>
This is a fixable code that can work on a table with any number of columns and any number of rows.
var table = document.querySelector('#my-table'),
trs = table.querySelectorAll('tr'),
outputDiv = document.querySelector('#output') ,
tds = [],
i, j,
output = '';
for (i = 0; i < trs.length; i += 1) {
tds = trs[i].querySelectorAll('td');
output += "Row #" + (i + 1) + "<br>";
for (j = 0; j < tds.length; j += 1) {
output += tds[j].innerText + ' ';
}
output += '<br>-----------------<br>';
}
outputDiv.innerHTML = output;
<table border=1 id="my-table">
<tr>
<td>Row1-Column1</td>
<td>Row1-Column2</td>
<td>Row1-Column3</td>
<td>Row1-Column4</td>
<td>Row1-Column5</td>
</tr>
<tr>
<td>Row2-Column1</td>
<td>Row2-Column2</td>
<td>Row2-Column3</td>
<td>Row2-Column4</td>
<td>Row2-Column5</td>
</tr>
<tr>
<td>Row3-Column1</td>
<td>Row3-Column2</td>
<td>Row3-Column3</td>
<td>Row3-Column4</td>
<td>Row3-Column5</td>
</tr>
</table>
<br>
<span style="font-weight: bold">Desired Output:</span> "Row1-Column1 Row1-Column2, Row2-Column1 Row2-Column2, Row3-Column1 Row3-Column2"
<br>
<br>
<span>Output:</span> <div id="output"></div>
JSFiddle

Adding rows to table with jquery

I have a html table like this:
Group Amount
x 3
x 1
test 2
test 5
But I would like to have this:
Group Amount
x 3
x 1
sum x 4
test 2
test 5
sum test 7
I already can add a row at a index:
$('.mytable > tbody > tr').eq(i-1).after(html);
But how could I get the index and the sum with jquery?
This will do what you need, for all future groups, with the values in any order, but I'd strongly recommend doing all this on the server when you first get the information....
var groups = {};
// get the sums of all the groups in the table, and the index of the last row of each
$(".mytable tbody tr").each(function(i) {
var group = $(this).find("td").eq(0).text();
var value = parseInt($(this).find("td").eq(1).text(), 10);
if (groups.hasOwnProperty(group)) {
groups[group].sum += value;
}
else {
groups[group] = {
sum: value
};
}
groups[group].index = i;
});
// convert the group information into an array so it can be sorted...
var groupArray = [];
for(var group in groups) {
groups[group].name = group;
groupArray.push(groups[group]);
}
// sort the groups in reverse index order
groupArray = groupArray.sort(function(a, b) {
return b.index - a.index;
});
// parse the groups of values and add them to the table, after the final row of each group
for (var i = 0, l = groupArray.length; i < l; i++) {
$(".mytable tbody tr").eq(groupArray[i].index).after("<tr><td>Sum " + groupArray[i].name + "</td><td>" + groupArray[i].sum + "</td></tr>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="mytable">
<thead>
<tr>
<th>Group</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>3</td>
</tr>
<tr>
<td>x</td>
<td>1</td>
</tr>
<tr>
<td>test</td>
<td>2</td>
</tr>
<tr>
<td>test</td>
<td>5</td>
</tr>
</tbody>
</table>
Please try this one.
var sums = [];
$("table.mytable tbody tr").each(function(index) {
var label = $(this).find("td:first-child").html();
var value = parseInt($(this).find("td:last-child").html());
if (sums.length == 0 || sums[sums.length - 1].label != label)
sums.push({
index: index,
label: label,
sum: value
});
else
sums[sums.length - 1].sum += value;
});
for (var i = 0; i < sums.length; i++)
$('table.mytable > tbody > tr').eq(sums[i].index + i).after("<tr><td>" + sums[i].label + "</td><td>" + sums[i].sum + "</td></tr>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="mytable">
<thead>
<tr>
<th>Group</th>
<th>Amount</th>
</tr>
<thead>
<tbody>
<tr>
<td>x</td>
<td>3</td>
</tr>
<tr>
<td>x</td>
<td>1</td>
</tr>
<tr>
<td>test</td>
<td>2</td>
</tr>
<tr>
<td>test</td>
<td>5</td>
</tr>
</tbody>
</table>
The row index you can use de .rowIndex property of the table row element ($tr[0].rowIndex).
The sum, you would have to iterate over the elements, if you elements are ordered by group:
var group, sum = 0;
$('table tr').each(function () {
var $tr = $(this);
if (!group)
group = $tr.children('td:first-child').text();
sum += parseFloat($tr.children('td:last-child').text());
if ($tr.next().children('td:first-child').text() !== group) {
$tr.after('<tr><td>sum of ' + group + '</td><td>' + sum + '</td></tr>');
sum = 0;
group = null;
}
});
Although you can achieve the desired result with that, I encourage you not to do this. You are strongly relying on the data and HTML structure. Your code is going to be fragile, hard to maintain and, probably, with poor performance.

how to use javascript or jquery create table fast

I want to create a table by click a button,and i need to save the table to the database .this is the code to create table but i think this is so long,how can i create it fast?
var div = document.createElement("div");
var table1 = document.createElement("table");
var table2 =document.createElement("table");
var thead = document.createElement("thead");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
var th3 = document.createElement("th");
th1.innerHTML="Count";
th2.innerHTML="Date";
th3.innerHTML="Price";
document.body.appendChild(div);
div.appendChild(table1);
div.appendChild(table2);
table2.appendChild(thead);
thead.appendChild(th1);
thead.appendChild(th2);
thead.appendChild(th3);
If the code is too long then I recommend creating an html table structure inside a div that is not displayed. Then when the user clicks the button then you could
Display the table that is hidden.
Clone the table and append it to something (if you expect to create the table multiple times)
Your code would then look like so (cloning wise):
jQuery:
$('#myButton').on('click', function(){
$(document.body).append($('original').clone());
});
Javascript:
document.getElementById('myButton').onclick = function(){
document.body.appendChild(document.getElementById('original').cloneNode());
}
And here is the html table you can have hidden.
<div style="display: none;">
<table id="original">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
This reduces greatly your javascript code.
If you want to make some enhancement than you can use precompiled template like muchtache.js :
<table>
<tr>
<th> Count </th>
<th> Date </th>
<th> Price </th>
</tr>
{{#jsonObject}}
<tr>
<td>{{Count1}}</td>
<td>{{Date1}}</td>
<td>{{Price1}}</td>
</tr>
{{/jsonObject}}
</table>
in javascript, you can write your javascript jsonobject as :
jsonobject : [{
count1 : 1,
date1 : 12/12/2012,
price1 : 100
},
{
count1 : 2,
date1 : 12/12/2013,
price1 : 200
}
]
for full muchtache example visit Json Object into Mustache.js Table
The following function might help:
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
Here is how to use it:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<table></table>'
+ '<table>'
+ '<thead>'
+ '<th>Count</th>'
+ '<th>Date</th>'
+ '<th>Price</th>'
+ '</thead>'
+ '</table>'
+ '</div>'
));
Live demo:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<p>Paragraph.</p>'
+ '<ul>'
+ '<li>Item 1.</li>'
+ '<li>Item 2.</li>'
+ '<li>Item 3.</li>'
+ '</ul>'
+ '</div>'
));
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}

How to read HTML <table> and sort the table content?

I have a html table with three columns [Title, Category, Sub-Category] and multiple rows . And I want to read the entire table content and make it categorized as below output.
My <html> table content is like this.
Title Category Sub
T1 C1 S1
T2 C2 S2
T3 C2 S3
T3 C1 S1
T2 C1 S3
T1 C2 S3
Here is the output format what I really need. I just want to print the above html table content in the below out put format.
T1 :
C1 : S1
C2 : S3
T2 :
C2 : S2
C1 : S3
T3 :
C2 : S3
C1 : S3
[Title]
[Category] :[Sub-Category]
Please help me.
Assuming the table has this code:
<table>
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Sub</th>
</tr>
</thead>
<tbody>
<tr>
<th>T1</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C2</td>
<td>S2</td>
</tr>
<tr>
<th>T3</th>
<td>C2</td>
<td>S3</td>
</tr>
<tr>
<th>T3</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C1</td>
<td>S3</td>
</tr>
<tr>
<th>T1</th>
<td>C2</td>
<td>S3</td>
</tr>
</tbody>
</table>
We can use jQuery to get output like this:
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = "";
$("tbody tr").each(function(){
s += $(this).find("th").html() + ":\n";
s += $(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html() + "\n\n";
});
$("textarea").val(s);
});
Fiddle: http://jsfiddle.net/praveenscience/9ueervw4/
The below code, you get a JavaScript object which is associative!
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = {};
$("tbody tr").each(function(){
if (!s[$(this).find("th").html()])
s[$(this).find("th").html()] = [];
s[$(this).find("th").html()].push($(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html());
});
});
Try using associative arrays in javascript/jQuery: DEMO
var tableRowArray = $('table tr');
var titleArray = [];
var mainArray = {};
// build an associative array of the values int he table
tableRowArray.each(function(){
if($(this).children('th').length == 0) {
var tempTitle = $(this).children('td').eq(0).text();
if(mainArray[tempTitle]){
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
else {
titleArray.push(tempTitle);
mainArray[tempTitle] = {};
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
}
});
// print the formatted associative array to the page
$('body').append("<p></p>");
var formattedString = "";
$.each(titleArray, function(index, value){
formattedString += "<b>" + value + " : </b><br/>";
for(var key in mainArray[value]) {
formattedString += " " + key + " : " + mainArray[value][key] + "<br/>";
}
});
$('p').html(formattedString);
Basically, we create an associative array from your table and then the next piece iterates through the array to print it in the format you specified (you may need to edit the set up of the array if you table structure varies from what I used the in JSfiddle).
The below example will give you the output you want.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script language="javascript">
$(document).ready(function () {
var outputtemp = "<table>";
$("#tbl1 tr").not("tr th").each(function () {
outputtemp += "<tr>"
var i = 0;
$(this).find("td").each(function () {
if (i == 0)
outputtemp += "<td>" + $(this).text() + ":</td></tr><tr>";
else if (i == 1)
outputtemp += "<td></td><td>" + $(this).text() + ":</td>";
else
outputtemp += "<td>" + $(this).text() + "</td>";
i++;
});
outputtemp += "</tr>"
});
outputtemp += "</table>"
$(".output").html(outputtemp);
});
</script>
</head>
<body>
<table id="tbl1">
<tr>
<th>
Title
</th>
<th>
Category
</th>
<th>
Sub
</th>
</tr>
<tr>
<td>
T1
</td>
<td>
C1
</td>
<td>
S1
</td>
</tr>
<tr>
<td>
T2
</td>
<td>
C2
</td>
<td>
S2
</td>
</tr>
<tr>
<td>
T3
</td>
<td>
C3
</td>
<td>
S3
</td>
</tr>
</table>
<div class="output">
</div>
</body>
</html>
Get the data using getElementbyId and then you may apply any operation on that data when you have whole data in js variables.

Get Cell Location

So I have this table, and when I click on a td I would like to know where is that(which row and cell) without any attributes on the elements.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td> // If I click on this I would like to know tr:1 & td:2
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
Javascript:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
// Track my location;
// example: I'm in table row 1 and I'm the 2th cell of this row
}
}
In the handler, this is the table cell, so for the cell index do this:
var cellIndex = this.cellIndex + 1; // the + 1 is to give a 1 based index
and for the row index, do this:
var rowIndex = this.parentNode.rowIndex + 1;
Example: http://jsfiddle.net/fwZTc/1/
This script block will provide you the information you desire, by adding the information as properties to the cell and then accessing them in the onclick function:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
// Get all the rows in the table
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
//Get the cells in the given row
var cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// Cell Object
var cell = cells[j];
cell.rowIndex = i;
cell.positionIndex = j;
cell.totalCells = cells.length;
cell.totalRows = rows.length;
// Track with onclick
console.log(cell);
cell.onclick = function () {
alert("I am in row " + this.rowIndex + " (out of " + this.totalRows + " rows) and I am position " + this.positionIndex + " (out of " + this.totalCells + " cells)");
};
}
}
Well, When you have rowspan/colspan you can have a lot more fun, however, if the grid is regular, you can just determine your position from the index by doing:
row = Math.floor(i / rows);
column = i % columns;
Using "this" on cells table
function myFunction(x) {
var tr = x.parentNode.rowIndex;
var td = x.cellIndex;
document.getElementById("tr").innerHTML = "Row index is: " + tr;
document.getElementById("td").innerHTML = "Column index is: " + td;
}
tr, th, td {
padding: 0.6rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td onclick="myFunction(this)">1</td>
<td onclick="myFunction(this)">2</td>
<td onclick="myFunction(this)">3</td>
</tr>
<tr>
<td onclick="myFunction(this)">4</td>
<td onclick="myFunction(this)">5</td>
<td onclick="myFunction(this)">6</td>
</tr>
<tr>
<td onclick="myFunction(this)">7</td>
<td onclick="myFunction(this)">8</td>
<td onclick="myFunction(this)">9</td>
</tr>
</tbody>
</table>
<p id="tr"></p>
<p id="td"></p>

Categories