0

Long story short - I'm displaying stock trades table and trying to set table row colors red or green meaning it's 'buy' or 'sell'.

<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>board</th> <th>buysell</th> <th>openinterest</th> <th>price</th> <th>quantity</th> <th>seccode</th> <th>secid</th> <th>time</th> <th>tradeno</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>FUT</td> <td>B</td> <td>2912686</td> <td>67686</td> <td>100</td> <td>SiZ5</td> <td>3630</td> <td>23.09.2015 11:12:27</td> <td>1239572664</td> </tr> 

...etc

using jQuery:

$("tr:contains('B')").addClass('greenBg'); $("tr:contains('S')").addClass('redBg'); 

but it actually colors row based on all content.

So, how should I address it to check only 'buysell' cell value ('B' to greenBg, 'S' to redBg) and set color to the whole row, not only first cell?

Thanks in advance!

3 Answers 3

4

This is one way of doing it:

var classes = { 'B': 'greenBg', 'S': 'redBg' }; $('table.dataframe tbody tr').addClass(function() { return classes[this.cells[2].textContent]; }); 

If there is no corresponding key for the cell's textContent (textContent is not B or S), the function returns undefined and addClass doesn't add any class to that row.

Sign up to request clarification or add additional context in comments.

Comments

0
$(document).ready(function(){ $('table.dataframe tr td').each(function(){ if($(this).text() == 'B'){ $(this).addClass('greenBg'); //colors the td //$(this).parent().addClass('greenBg'); //colors the entire row } else if($(this).text() == 'S'){ $(this).addClass('redBg'); //$(this).parent().addClass('redBg'); //colors the entire row } }); }); 

2 Comments

Thank you vey much! This helped a lot!
@pmus if this helped ..then you can accept the answer
0

You can check for the td or the tr of the nth-child. So that it's only check for the table cell/row of the value you want.

I've done two examples one of colouring the whole row or just colouring the selected td's

// Checks through the td elements which contain 'B' or 'S' $("td:nth-child(3):contains('B')").addClass('greenBg'); $("td:nth-child(3):contains('S')").addClass('redBg'); 

JSFIDDLE EXAMPLE (Color to only the TD)

// Checks through tr elements and find the td elements which contain 'B' or 'S' $("tr:has(td:nth-child(3):contains('B'))").addClass('greenBg'); $("tr:has(td:nth-child(3):contains('S'))").addClass('redBg'); 

JS FIDDLE EXAMPLE (Color to the whole row)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.