[Django]-DJANGO – Change text color based on value (HTML & JS)

8👍

I want to change the number’s color to red when the number is negative, and to green when the number is positive. I know I need to use JS for this but I could not make it work.

You really don’t need to do this in JS, so I’ve offered this as an alternative which both solves the original problem and simplifies your code. If you have limited programming experience, you may be better taking the simpler route of managing this using the Django template, rather than a fairly lengthy JS solution. Of course, if you want to fix the JS and use that because it’s necessary for other reasons on your site, then the other answers will fix it. 🙂

I’ve cut this down for the sake of readability as an answer. (It’s also bad practice to have both a CSS file and styling inline!)

        <tr>
            <td>{{ transaction.TransactionFrom }}</td>
            <td>{{ transaction.TransactionTo }}</td> 
            <td>
                {% if transaction.TransactionAmount < 0 %}
                <div class="TransactionAmount NegativeTransaction"> 
                {% else %} 
                <div class="TransactionAmount PositiveTransaction">
                {% endif %}
                     {{ transaction.TransactionAmount }}
                </div>
            </td>
            <td>{{ transaction.BalanceAfterTransaction }}</td>
            <td><a href="{% url 'WalletJournal:detail' transaction.id %}">{{ transaction.TransactionDateTime }}...</a></td>
            <td>{{ transaction.TransactionComment }}</td>
        </tr>

And the appropriate CSS:

.NegativeTransaction {
  color: #FF0000;
}

.PositiveTransaction.green {
  color: #33FF3C;
}

2👍

In your html code you’ve defined ‘TransactionAmount’ as a class for your td elements, while in the css, you’ve defined rules considering ‘TransactionAmount’ as an id: #TransactionAmount and #TransactionAmount.green. So, changing the rules to .TransactionAmount and .TransactionAmount.green should fix your code.

1👍

Your code seems to work fine when I tested it. I just had to add the red class.

var els = document.getElementsByClassName('TransactionAmount');
for (var i = 0; i < els.length; i++) {
  var cell = els[i];
  if (cell.textContent < 0) {
    cell.classList.remove('green')
    cell.classList.add('red')
  } else {
    cell.classList.remove('red');
    cell.classList.add('green');
  }
}

Also, maybe you simply forgot your CSS for .green and .red, since it’s not present in the CSS code you provided above.

Here, take a look at it in JSFiddle

.

Leave a comment