Search code examples
javascripthtmldjangohtml-table

Conditionally changing the formatting of cells in a loop-generated table


My django app generates a table on the basis of the python dictionary "participants". To do that, it uses the HTML code below, which features a loop that run through all the *elements* of "participants". The table is generated without any problems.

Now I want to conditionally change the background color of the column with the value "balance", depending on whether that value is > 0, < 0, or = 0. To that purpose, I have inserted javascript at the bottom of the HTML body. But this has no effect whatsoever. How can the code be fixed?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Participants</title>
</head>
<body>

<h1>Participants</h1>

<table id="participants_table" border="1">

    {% for x in participants %}
    <tr>    
        <td>{{ x.firstName }}</td>
        <td>{{ x.lastName }}</td>
        <td class="balance">{{ x.balance }}</td> 
    </tr>
    {% endfor %}

</table>

<script>
        var balance = document.getElementById('participants_table').getElementsByClassName('balance');
        if (balance.innerHTML > 0){
            balance.style.backgroundColor='#003F87';
        } else if (balance.innerHTML < 0) {
            balance.style.backgroundColor='#0033H7';
        } else {
            balance.style.backgroundColor='#0093H7';
        }
</script>

</body>
</html>

Solution

  • Theoretically this should work.

    <td style=background-color: "{% if x.balance > 0 %}#003F87{% elif 
     x.balance < 0 %}#0033H7 {%else%)#0093H7{% endif %}">{{ x.balance 
    }}</td> 
    

    So I am using inline styling(not recommended) and conditionally rendering the bg color. If you're using something like Bootstrap, then it may be cleaner like this:

     <td class="{% if x.balance > 0 %}bg-primary{% elif x.balance < 0 
     %}bg-warning{%else%)bg-secondary{% endif %}>{{ x.balance }}</td>