tags:

views:

59

answers:

4

I have a html table similar to this:

<table>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Some text...</td>
  </tr>
</table>

The cells in the first column contain a numeric value of 1, 2 or 3.

I’m looking for a neat way of transforming this value into something more “graphical” using a client side approach such as CSS (preferably) or jQuery. For example, instead of “1” the cell content should be rendered as an icon, or a dot with a red color. Just setting the background color would also be ok.

UPDATE:

Thanks for all the suggestions. It seems it was just the Each method from jQuery I was missing. :)

Here's my final code. I wrapped it in separate function which is called on document ready and after table updates.

function fnTransformIcons() 
{ 
  var color;

  $("td.Icon").each(function() { 
  var value = $(this).html();

  switch (parseInt(value))
  { 
    case 0 : color = 'white'; break;
    case 1 : color = 'red'; break; 
    case 2 : color = 'green'; break; 
    case 3 : color = 'yellow'; break;
  } 
  $(this).css("backgroundColor", color); 
  });     
}
+1  A: 

For jQuery, try

$("tr td:first").each(function(){
   // do transformations like $(this).html(...)
});
Eli
+3  A: 
$(document).ready( function() {
    $("tr").each( function() {
        switch ($("td:first",this).text()) {
            case '1': color = 'red'; break;
            case '2': color = 'blue'; break;
            default: color = 'green';
        }
        $($("td:first",this).css("backgroundColor", color);
    });
});

Thanks Eikern for the tip.

enbuyukfener
How about replacing `$(this).children().first().text()` with `$("td:first",this).text()`?
Eikern
+1  A: 

Yet another solution:

$("tr td:first").each( function() {
    $(this).addClass('my_custom_class_'+$(this).text());
});

CSS:

.my_custom_class_1 { background: red; }
.my_custom_class_2 { background: green; }
/* etc. */
Darmen
+1  A: 
emmychan