Compare tabledatas and add CSS if the tabledata is - javascript

I have a HTML-table with several tablerows. Each row contains 2 tabledata elements.
These td elements are filled with numbers.
I need code that helps me compare the numbers of each row and add CSS.
An example:
<tr>
<td>12</td>
<td>15</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
We are always going to use CSS on the second tabledata element. If the value of the second td is lesser than the value of the first td element, it has to appear in red color.
On the other hand, if the value of the second td element is greater than the value of the first td element it has to appear in green color.
This means that the tables contents should look something like this:
<tr>
<td>12</td>
<td style='color:green;'>15</td>
</tr>
<tr>
<td>3</td>
<td style='color:red;'>1</td>
</tr>
How can this be done?

You can use jQuery to get the inner values of each td element, compare the values and apply a style given the output. This assumes you always have two td elements. Any more and you would have to loop each td in the row and keep a running count.
$("table tr").each(function(){
var firstTd = $(this).children(":first");
var secondTd = $(this).children(":last");
if (secondTd.html() < firstTd.html()) {
secondTd.css("background-color", "red");
} else if (secondTd.html() > firstTd.html()) {
secondTd.css("background-color", "green");
}
});
JSFiddle

You can try with this function: link to fiddle
This solution is without using JQuery of course.
Just in case, I also post the code here:
<body onload="myFunction()">
<table>
<tr>
<td>12</td>
<td>15</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
</table>
</body>
<script>
function myFunction(){
var tds = document.getElementsByTagName("td");
for (var i=0; i<tds.length; i++){
if (i>=1 && i%2 != 0){
if (parseInt(tds[i].innerText) > parseInt(tds[i-1].innerText)) {
tds[i].style.color = "green";
} else {
tds[i].style.color = "red";
}
}
}
}
</script>

Related

jQuery .nextAll() is not working with html table columns

I have a html table as below:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
On click of a td I am changing the color of it's next 4 td's and for that I have done it in jquery as below:
$(this).nextAll("td").slice(0, 4).addClass("selected");
Above code is working if I click on 1st TD then it selects further 4 td's but if I click on 4th td then it selects only 5th td. I want it to select another 3 td's in next row as well.
Please tell me how can I fix this?
jQuery .index() method returns the index of passed element in the current set. By using returned index you can .slice() the collection, this is more efficient than querying the DOM on each click, especially when you have a big table:
var $tds = $('#table td').on('click', function() {
var i = $tds.index(this);
$tds.slice(++i, i+4).addClass("selected");
});
http://jsfiddle.net/MamYX/
You can simply add the td of the following row. :
$(this).nextAll("td").add($(this).closest('tr').nextAll().find('td'))
.slice(0, 4).addClass("selected");
Demonstration
var $tds = $('table td').click(function(){
var idx = $tds.index(this);
$tds.filter(':gt(' + idx + '):lt(4)').addClass('selected')
})
Demo: Fiddle

background color using html n css

I'm trying to loop through a table to get each TD value. If the value is below a specific number then I'll do something.
</head>
<body>
<table id="tableData" name="tableData">
<tr>
<td>abc</td>
<td>5</td>
<td>abcd</td>
</tr>
<tr>
<td>aaaa</td>
<td>15</td>
<td>bbbb</td>
</tr>
<tr>
<td>ccc</td>
<td>25</td>
<td>dddd</td>
</tr>
</table>
</body>
above is my code .. i need to change the background colors of the 2nd column as below . if the value of the 2nd column element is <= 10 then the color is green , from 11-20 its yellow and above 21 its red.
I have given the sample code here. actually in real , the table is derived from the database , iy may have any nomber of rows. so i need to color the column as the page gets loaded.
Any help is appreciated, thanks.
The following modified plain JavaScript will colour the <td> elements as required:
function checkForm() {
var tds = document.querySelectorAll('td[id]');
for (var j = 0; j < tds.length; j++) {
var i = tds[j].innerHTML;
if(i < 10){
tds[j].style.backgroundColor = 'green';
} else if(i >= 11 && i <= 20){
tds[j].style.backgroundColor = 'yellow';
} else if(i > 20){
tds[j].style.backgroundColor = 'red';
}
}
}
but you will need to modify the HTML to give the <td>s unique ID values, for example
<body onload="checkForm();">
<table id="tableData" name="tableData">
<tr>
<td>abc</td>
<td id="a">5</td>
<td>abcd</td>
</tr>
<tr>
<td>aaaa</td>
<td id="b">15</td>
<td>bbbb</td>
</tr>
<tr>
<td>ccc</td>
<td id="c">25</td>
<td>dddd</td>
</tr>
</table>
</body>
If it is always the middle cell that needs colour you could remove the ids completely and rely on the fact that is is "always the middle cell". For example use the following selector instead:
var tds = document.querySelectorAll('td:nth-child(2)');
The only limitation is that querySelectorAll is that it is not supported by IE<9. All other browsers support it.
Since the cell that requires a background-color is always the 2nd cell, you can use the CSS nth-child selector as the argument to in querySelectorAll() to "select the 2nd <td> child element of the parent", which in this case is the <tr>.
So td:nth-child(2) finds the the <td>two</td> element for the following HTML:
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
See some examples of how :nth-child works.
Demo of id-less solution (for if the cell to colour is always the middle one).
Since OP is stuck with IE8 and IE8 does not support :nth-child an alternative adjacent sibling combinator can be used to target the 2nd child with the caveats that there must only be 3 <td> and the 3rd must not contain any numbers.
Update:
Based on the actual requirements of needing to work in IE8 and add background-color to the 6th column, here is a simpler (to read) and more cross-browser compatible jQuery solution:
jsBin demo (so it works on IE8)
HTML
Remove the onload="checkForm(); from <body>
<table id="tableData" name="tableData">
<tr>
<td></td><td></td><td></td><td></td>
<td>abc</td>
<td>5</td>
<td>abcd</td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td>aaaa</td>
<td>15</td>
<td>bbbb</td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td>ccc</td>
<td>25</td>
<td>dddd</td>
</tr>
</table>
JavaScript
$(function(){
var tds = $('td:nth-child(6)');
for (var j = 0; j < tds.length; j++) {
var i = tds[j].innerHTML;
if(i < 10){
tds[j].style.backgroundColor = 'green';
} else if(i >= 11 && i <= 20){
tds[j].style.backgroundColor = 'yellow';
} else if(i > 20){
tds[j].style.backgroundColor = 'red';
}
}
});
First off, don't use the same ID's for any elements on a page. It is a unique identifier. If you want to reference more than one element, then use a class instead.
The simplest way to achieve what you want is using two classes - one to define xxx, and then one to define its status (colour). Also, if you use semantic naming (instead of .green,.yellow,.red) you will get good understanding of your code.
ex
.xxx{ font-weight: bold;}
.less10 { background: green;}
.between1120 {background: yellow; }
.over21 { background: red; }
You cannot set CSS depending on the content inside the element. For this you would need some simple jQuery/javascript or your chosen programming language to loop through all the xxx-classes in the table, and add the status class accordingly.
ex
<td class="xxx less10">5</td>
<td class="xxx between1120">15</td>
<td class="xxx over21">35</td>
Firstly you should change the ID xxx to Class xxx.
function checkForm(){
$('td.xxx').each(function(){
var val=parseInt($(this).text());
if(val<=10) $(this).css({background:'green'});
else if(val>10 && val<=20) $(this).css({background:'yellow'});
else if(val>20) $(this).css({background:'red'});
}
}
I think that should work with jQuery.
Here is what you want :
Demo Here</>
<table id="tableData" name="tableData">
<tr>
<td>
abc
</td>
<td class="xxx">
5
</td>
<td>
abcd
</td>
</tr>
<tr>
<td>
aaaa
</td>
<td class="xxx">
15
</td>
<td>
bbbb
</td>
</tr>
<tr>
<td>
ccc
</td>
<td class="xxx">
25
</td>
<td>
dddd
</td>
</tr>
</table>
Javascript
$(document).ready(function () {
var arr = $(".xxx").toArray();
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].innerText) < 10) {
$(arr[i])[0].bgColor = "green";
}
else if (parseInt(arr[i].innerText) >= 11 && parseInt(arr[i].innerText) <= 20) {
$(arr[i])[0].bgColor = 'yellow';
}
else if (parseInt(arr[i].innerText) > 20) {
$(arr[i])[0].bgColor = 'red';
}
}
});

an easy way to get all the table rows from a table without using a loop

Is there an easy way to get all the table rows from a table without using a loop.
I thought that this would work but it only alerts the first row.
http://jsfiddle.net/THPWy/
$(document).ready(function () {
var O = $('#mainTable').find('tr');
//var O = $('#mainTable tr');
alert(O.html());
//alerts <th>Month</th><th>Savings</th>
});
<table id ="mainTable" border="1">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
<tr>
<td>March</td>
<td>$50</td>
</tr>
<tr>
<td>a</td>
<td>$50</td>
</tr>
<tr>
<td>m</td>
<td>$50</td>
</tr>
<tr>
<td>j</td>
<td>$50</td>
</tr>
<tr>
<td>july</td>
<td>$50</td>
</tr>
<tr>
<td>aug</td>
<td>$50</td>
</tr>
<tr>
<td>sep</td>
<td>$50</td>
</tr>
</table>
Whatever you use will be iterating through each row to get the inner HTML out of it. So no, you cannot do it without a loop.
Here is an alternate method that gets the message in one line if that's what you're after, it's slightly less efficient than going with a loop though as it needs to make a new array.
jsFiddle
$(document).ready(function () {
var rows = $('#mainTable tr');
var message = $.map(rows, function (v) {
return v.innerHTML;
}).join('\n');
alert(message);
});
I would recommend just doing it in a regular loop.
FYI .html() only alerts the first row because that's what it was designed to do as that is what would be most useful.
Description: Get the HTML contents of the first element in the set of matched elements.
What about:
// get all tr (excluding the caption)
var O = $('table#mainTable').children().slice(1);
http://jsfiddle.net/THPWy/7/
What you have in your code already retrieves all table rows as an array of jQuery elements:
var trs = $('#mainTable').find('tr');
If you want to print the html contents of each row then you would have to use a loop:
trs.each(function (index, element) {
alert($(this).html());
});
You can get by using
gt(), lt(),eq()
.gt(index) // will get all the rows greater than specified index
.lt(index) // will get all the rows less than specified index
.eq(index) // will get all the rows equal to specified index
For Example
$('#mainTable tr').eq(1) will give second row
But when you want to know all the table rows data then go with Konstantin D - Infragistics solution

Hide a `tr` based on the values of `td` in the table using jQuery

I have table that is filled with dynamic content from a query from a database on the backend. I want to hide any tr that contains only zeros.
Here is what my table looks like:
<table id="table1" " cellspacing="0" style="width: 800px">
<thead id="tablehead">
</thead>
<tbody id="tabledata">
<tr class="odd">
<td>0</td>
<td>0</td>
<td>0</td>
<td>0.00%</td>
<td>0.00%</td>
<td>$0.00</td>
<td>$0.00</td>
<td>$0.00</td>
<td>$0.00</td>
<td>$0.00</td>
<td>$0.00</td>
</tr>
</tbody>
Now if the first three td's in tbody are == 0 then I would like to add a class to the tr that will effectively hide that row. How would I go about doing this using jQuery?
EDIT:
Sorry forgot to add what I have tried. The following is a test script I tried to see if I could collect all the td's
$(document).ready(function() {
$("#table1 td").filter(function() {
return $(this).text == 0;
}).css("text-color", "red");
});
You can do this :
$('tr').each(function(){
var tr = $(this);
if (tr.find('td:eq(0)').text()=="0"
&& tr.find('td:eq(1)').text()=="0"
&& tr.find('td:eq(2)').text()=="0"
) tr.addClass('hidden');
});
Demonstration (the hidden class changes the color to red, it's clearer...)
Depending on your need, you might have to trim the texts, or to parse them.
For more complex tests, you might find useful to work directly with an array of the cell contents. You can get it using
var celltexts = tr.find('td').map(function(){return $(this).text()}).toArray();

HTML and JavaScript auto increment number

I am new to HTML and JavaScript. I got a problem like this in HTML (This code below only visualize the problem for you to easy to reference.)
<tr>
<td>1</td>
<td>Harry</td>
</tr>
<tr>
<td>2</td>
<td>Simon</td>
</tr>
<td>3</td>
<td>Maria</td>
</tr>
</tr>
<td>4</td>
<td>Victory</td>
</tr>
This is a name list, however the problem is that sometime i need to add more name into this table and I HAVE TO ADD in front of Number 1, so meaning i have to re-write the number list, (EX: 1 1 2 3 4 --> 1 2 3 4 5). I feel that is not a good way.
NOTE: I don't want to change the list number decrease from top to bottom. And this is a HTML file so can't apply PHP
Anyone can help me to make the number to a variable like "i" and a function can help me to fill variable i increment from top to bottom automatically like
<tr>
<td>i</td>
<td>Harry</td>
</tr>
<tr>
<td>i</td>
<td>Simon</td>
</tr>
<td>i</td>
<td>Maria</td>
</tr>
</tr>
<td>i</td>
<td>Victory</td>
</tr>
Function Fill_i for example:
I think that JavaScript should be used in this case. Thanks for your help and suggestion on this problem.
Again: I am not allowed to use PHP or ASP and when I add a new name, I add it manually by HTML.
You can use a css counter - MDN
table {
counter-reset: section;
}
.count:before {
counter-increment: section;
content: counter(section);
}
<table>
<tr>
<td class="count"></td>
<td>Harry</td>
</tr>
<tr>
<td class="count"></td>
<td>Simon</td>
</tr>
<tr>
<td class="count"></td>
<td>Maria</td>
</tr>
<tr>
<td class="count"></td>
<td>Victory</td>
</tr>
</table>
FIDDLE
This should work for you:
<table>
<tr>
<td>Harry</td>
</tr>
<tr>
<td>Simon</td>
</tr>
<tr>
<td>Maria</td>
</tr>
<tr>
<td>Victory</td>
</tr>
</table>
<script>
var tables = document.getElementsByTagName('table');
var table = tables[tables.length - 1];
var rows = table.rows;
for(var i = 0, td; i < rows.length; i++){
td = document.createElement('td');
td.appendChild(document.createTextNode(i + 1));
rows[i].insertBefore(td, rows[i].firstChild);
}
</script>
The script should be placed immediately after your table. It goes through each row of your table and adds an extra cell to the beginning with the incrementing number inside that cell.
JSFiddle Demo
Edit: seems like the other solution posted would work do (was added while I typed this up).
You really should be using PHP to do something dynamic like this, which would become trivial with a single for loop.
However, if you insist on using HTML/Javascript (or perhaps this is a 'static page'...) then what you are asking should be possible.
You could add a class to each of the <td> elements you want to use, so:
<tr>
<td class='personid'>i</td>
<td>Harry</td>
</tr>
<tr>
<td class='personid'>i</td>
<td>Simon</td>
</tr>
<td class='personid'>i</td>
<td>Maria</td>
</tr>
</tr>
<td class='personid'>i</td>
<td>Victory</td>
</tr>
Then you would have a javascript function that does something like this:
var list = document.getElementsByClassName("personid");
for (var i = 1; i <= list.length; i++) {
list[i].innerHTML = i;
}
Are you sure you don't want an ordered list?
<ol>
<li>Fred</li>
<li>Barry</li>
</ol>
<script>
function addRow(index, name){
var tbody = document.getElementById("nameList");
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(index));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(name));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}
var name=new Array();
name[0]="Harry";
name[1]="Simon";
name[2]="Maria";
name[3]="Victory";
for(var i=0; i < name.length; i++) {
addRow(i,name[i]);
}
</script>
<html>
<body>
<table id="nameList">
</table>
</body>
</html>
I would say do this (im going to assume you are not going to load in jquery or anything fancy):
<html>
<head>
<script type="text/javascript>
function writeTable(){
// list of names
var myList = [ "name1", "name2", "etc", "etc"];
// your variable to write your output
var outputTable = "<table>";
//the div to write the output to
var outputDiv = document.getElementById("output");
//the loop that writes the table
for (var i=0; i<myList.length; i++){
outputTable += "</tr><td>"+i+"</td><td>"+myList[i]+"</td></tr>";
}
//close the table
outputTable += "</table>";
//write the table
outputDiv.innerHTML = outputTable;
}
</script>
</head>
<body onload=writeTable()>
<div id='output'></div>
</body>
</html>
hope this helps :)
Try this
$(document).ready(function() {
var addSerialNumber = function () {
$('table tr').each(function(index) {
$(this).find('td:nth-child(1)').html(index);
});
};
addSerialNumber();
});

Categories

Resources