Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  25] [ 5]  / answers: 1 / hits: 37970  / 9 Years ago, wed, september 23, 2015, 12:00:00

I have an html table and I want to color the rows based on the value in the first column of that row. If the value is CONFIRMED I want to color the row green, and if it is UNCONFIRMED I want to color the row red.



The JS I am using to do this is:



$(function(){
$(tr).each(function(){
var col_val = $(this).find(td:eq(1)).text();
if (col_val == CONFIRMED){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});


The CSS looks like this:



.selected {
background-color: green;
color: #FFF;
}

.bad {
background-color: red;
color: #FFF;
}


The html table is generated from a pandas dataframe in my Django view and passed in like this:



<div class=table-responsive style=margin-left: 15%; margin-right: 15%; overflow:auto;>
{{ datatable | safe }}
</div>


The problem is that it's coloring all of my rows red. Can anyone tell me what I'm doing wrong?


More From » javascript

 Answers
42

Since you use ===CONFIRMED make sure it's really: UPPERCASE, and that there's no leading or ending spaces CONFIRMED or CONFIRMED in the HTML.



The code you're showing will color .selected the entire row whos :eq(1) TD has the CONFIRMED content:





$(function(){
$(tr).each(function(){
var col_val = $(this).find(td:eq(1)).text();
if (col_val == CONFIRMED){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});

.selected{
background-color:green;
}
.bad{
background-color:red;
}

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<table>
<tr>
<td>1</td><td>CONFIRMED</td>
</tr>
<tr>
<td>2</td><td>UNCONFIRMED</td>
</tr>
</table>





nothing bad about it.



if that's not what you see on your screen note that :eq() is index based, and elements index start at 0 so :eq(0) is probably what you want?



Another probable thing is that you don't have the exact content string set as CONFIRMED but probably there's some spaces before or after - so make sure to trim them using $.trim()



if( $.trim(col_val) === CONFIRMED )


if you additionally want to make your code even more flexible about the UPPERCASE or Capitalization you can do as:



if( $.trim(col_val.toLowerCase() ) === confirmed )
// Will work on CONFIRMED, Confirmed, conFIRMed etc

[#64951] Monday, September 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailie

Total Points: 25
Total Questions: 112
Total Answers: 111

Location: Belize
Member since Tue, Dec 8, 2020
4 Years ago
;