0

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.

4
  • 1
    But where is your actual code...? Commented May 24, 2013 at 7:22
  • 2
    Id's should be unique. Commented May 24, 2013 at 7:23
  • Thanks for the updated question. Could you change the id="xxx" to a more representative value please? As @Zenith states, id values must be unique. If those are your actual ids then that is your problem. Commented May 24, 2013 at 7:30
  • thanks !!! then should i do to color that specific column as i needed ? Commented May 24, 2013 at 7:33

4 Answers 4

1

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';
        }
    }
});
Sign up to request clarification or add additional context in comments.

13 Comments

Doesn't my demo do what you want? It colours the 2nd column based on the value of the cell.
hi .. im not the getting the answer . if i use the code var tds = document.querySelectorAll('td:nth-child(3)'); .
wat is meant my td:nth-child(3) . can u explain it clearly pls
Does the demo work for you? I'll update my answer to explain the CSS selector.
Also, you need the 2nd child, not the 3rd. So it's td:nth-child(2) and not td:nth-child(3)
|
1

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>

1 Comment

actually i am not getting u . il take of that id's. and my ll be like below <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> what shld i do to color the specific column .. u know the table actually a contains lots of values . it ll be retreived dynamically from database. so i needed to color accordingly as the page gets loaded itself. PLease help
1

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.

Comments

0

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';
            }
        }

    });

3 Comments

i dont know how to use a fiddle link. what shld i do after clicking it. i dont see any code . may not getting loaded
yes sure .. but im new to this blog .. today only i joined and posted my question . if u say how to put upvote il surely do it :)
there is two arrow head symbols in leftmost of my answer. just click up arrow. as simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.