Question

I have a table that is populated with random numbers and I need to have a color set to the background of each cell based on the number in that cell to an rgba color. Now these number change on refresh so colors should change if number values change. How can I go about this? Thanks!

HTML

<table class="table table-bordered">
<tbody>
    <tr>
        <td>636407029</td>
        <td>612541294</td>
        <td>870806031</td>
    </tr><tr>
        <td>110235053</td>
        <td>924102758</td>
        <td>221478283</td>
    </tr><tr>
        <td>572041102</td>
        <td>236316470</td>
        <td>781401130</td>
    </tr>
</tbody>
</table>
Was it helpful?

Solution

try like this

$(".table-bordered td").each(function(){
$(this).attr("bgcolor",$(this).html());
});

fiddle

html

<table>
<tbody>
<tr>
    <td bgcolor="636407029">636407029</td>
    <td>612541294</td>
    <td>870806031</td>
</tr><tr>
    <td>110235053</td>
    <td>924102758</td>
    <td>221478283</td>
</tr><tr>
    <td>572041102</td>
    <td>236316470</td>
    <td>781401130</td>
</tr>
</tbody>
 </table>

OTHER TIPS

This should work - if you write transformNumberToColour function that is.

$("td").each(function(){
    $element = $(this);
    val = Number($element.html());
    rgbColour = transformNumberToColour(val); // not shure how you want to do this
    $element.css('background-color', rgbColour);
});

You'll have to do something like:

$("td").each(function () {
    var new_color = make_color_from_content($(this).text());
    $(this).css("background-color", new_color);
});

Of course you will have to write some function (make_color_from_content) to convert the value from "636407029" -for example- to "rgba(xxx,xxx,xxx,x)".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top