3

I am having column name as 'Status'. If status is 'Pass' i need to show that row in green color. If 'fail' then red. How to do it in javascript?

for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].style.backgroundColor = "red";
    }
}

I tried this but it is not supported by browser. Kindly help. Thanks.

Anthony Grist
  • 37,428
  • 8
  • 62
  • 73

5 Answers5

0

Using jQuery you can try:

function CheckStatus(id) {
    var rows = $('#'+id).find("tr")
    $(rows).each(function(){
        var value =  $(this).find('td:first').text();
        if (value == 'Pass') {
            $(this).css('background', 'red');
        }
    });
}
Akhil Sekharan
  • 11,581
  • 6
  • 34
  • 54
0
for (i=0; i < rows.length; i++) {
    var value = document.getElementsByTagName("td")[i].firstChild.nodeValue;
    if (value == 'Pass') {
        document.getElementsByTagName("td")[i].style.backgroundColor = "green";
    }
else{ document.getElementsByTagName("td")[i].style.backgroundColor = "red";}
}

try this code (I didn't try yet though, thiss the idea what you need)

user1844626
  • 1,728
  • 7
  • 23
  • 35
0

I would use class names instead of setting the style but try this:

for (i=0; i < rows.length; i++) { 
   var value =  = rows[i].cells[0].firstChild.nodeValue;
   if (value == 'Pass') {
        rows[i].className = "red";
    } 
}
matpol
  • 3,014
  • 1
  • 12
  • 17
0

Styles can only be implemented on HTML elements e.g. text box, select, text etc. In your case you are trying to style a value of 'rows', which is not correct. You need to select the HTML element and then style it.

Something like this might help:

for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].getElementsByTagName("td")[0].firstChild.style.backgroundColor = "red";
    }
}
Virk Bilal
  • 560
  • 1
  • 3
  • 10
-1

you can try using the Jquery

   $(document).ready(function () { 
            $("#testResults tr").each(function () { 
                var row = $(this).find("td:nth-child(2)").text(); 
                if (row == 'Pass') { 
                    $(this).css('background-color', '#F00'); 
                } else { 
                    $(this).css({ 'background-color': '#0G0',}); 
                } 
            }); 
        }); 
Srinivas B
  • 1,721
  • 3
  • 14
  • 33