Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming tablecell content with CSS or jQuery

Tags:

html

jquery

css

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); 
  });     
}
like image 311
Jakob Gade Avatar asked Dec 11 '25 01:12

Jakob Gade


2 Answers

$(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.

like image 150
tanerkay Avatar answered Dec 13 '25 15:12

tanerkay


For jQuery, try

$("tr td:first").each(function(){
   // do transformations like $(this).html(...)
});
like image 34
Eli Avatar answered Dec 13 '25 13:12

Eli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!