3

I'm creating a table displayed in HTML with Django. 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. Any help will be greatly appreciated !!

Here is my Django HTML template (linked to my view) :

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'WalletJournal/style.css' %}" />

<div id="container">
<h1>Transaction Journal</h1>
</div>

<div id="container">
{% if latest_transaction_list %}
<table>
    <tr>
        <th>From</th>
        <th>To</th> 
        <th>Amount</th>
        <th>Balance</th>
        <th>Date/Time</th>
        <th>Comment</th>
    </tr>
    {% for transaction in latest_transaction_list %}
        <tr>
            <td style="color:white">{{ transaction.TransactionFrom }}</td>
            <td style="color:white">{{ transaction.TransactionTo }}</td> 
            <td style="font-family:'Arial',serif;font-size:10pt"><div class="TransactionAmount">{{ transaction.TransactionAmount }}</div></td>
            <td style="font-family:'Arial',serif;font-size:10pt">{{ transaction.BalanceAfterTransaction }}</td>
            <td style="font-size:6pt"><a href="{% url 'WalletJournal:detail' transaction.id %}">{{ transaction.TransactionDateTime }}...</a></td>
            <td style="color:white">{{ transaction.TransactionComment }}</td>
        </tr>
    {% endfor %}
</table>
{% else %}
    <p>No transactions are available.</p>
{% endif %}
</div>

<script>
    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')
  } else {
    cell.classList.add('green');
  }
}
</script>

I know the JS code actually works since I got it from my previous question and I tested it outside of my project. Unfortunately my numbers stay gray and don't change color. Even if I use a number like "1" or "-1" instead of {{ transaction.TransactionAmount }}, it still shows up in gray (I tried removing the gray basecolor from the CSS too but it didn't work).

Here's my CSS :

@font-face {
    font-family: Eve;
    src: url('eve.ttf');
}

@font-face {
    font-family: Retro;
    src: url('retro.ttf');
}  

body {
    background: white url("images/background.gif") no-repeat right bottom;
}

h1 {
    font-family: Eve;
    color: white;
    font-size:35pt;
    text-align:center;
}

h2 {
    font-family: Eve;
    color: white;
    font-size:20pt;
    text-align:center;
}

a:link {
    color:#008000;
    text-decoration:none;
}

a:visited {
    color:#E09016;
    text-decoration:none;
}

table, td {
    font-family: Retro;
    border-style:solid;
    border-color:#3A5779;
    border-width:5px 5px 5px 13px;
    background:#1B2741;
    font-size:10pt;
    color:gray;
    padding:8px;
}

th {
    font-family: Eve;
    border-style:solid;
    border-color:#3A5779;
    border-width:5px 5px 5px 13px;
    background:#1B2741;
    font-size:14pt;
    color:white;
    padding:15px;
}

#container {
  margin: 0 auto;
  width: 1000px;
  text-align: center;
}

#TransactionAmount {
  color: #FF0000;
}

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

And in case it can help, here's the model I use in Django:

from django.db import models

# Create your models here.
class Transaction(models.Model):
    TransactionAmount = models.FloatField("Amount", max_length=75)
    BalanceAfterTransaction = models.FloatField("Balance", max_length=75)
    TransactionDateTime = models.DateTimeField("Date & Time")
    TransactionComment = models.CharField("Comment", max_length=75)
    TransactionFrom = models.CharField("From", max_length=75)
    TransactionTo = models.CharField("To", max_length=75)

    def __str__(self):
        return self.TransactionComment

Keep in mind I have limited programming experience, and thx a lot for helping !

6
  • Put debugger in script tag, try to find the value of cell.textContent Commented Mar 11, 2017 at 10:02
  • Can you please get rid of most of that code and just share the bit you're interested in - this is not a good way to ask questions Commented Mar 11, 2017 at 10:02
  • Ids have to be unique (id="container") and TransactionAmount is a class and not an id (#TransactionAmount, #TransactionAmount.green) Commented Mar 11, 2017 at 10:02
  • Well if I get rid of part of the code I'm afraid I'll remove what's actually causing the error. Commented Mar 11, 2017 at 10:04
  • I appreciate you already have the JS code, but do you need/want to do it in JS? It's much simpler to just do it in the Django template code. Commented Mar 11, 2017 at 10:26

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is indeed a lot better, I thought I couldn't do it without JS. Thx a lot :D
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 Comment

You were exactly right, thanks a lot. In the end, Whitnail provided a much more efficient way to do this natively with django (see above).
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

.

4 Comments

But only because you've fixed the wrong CSS rule where TransactionAmount is defined as an id instead of a class: #TransactionAmount, #TransactionAmount.green ;)
@Andreas I don't know what you mean. I did not touch any CSS code specifically for #TransactionAmount, since there is none to begin with.
Simple mistake on my part, I got confused when trying several solutions. It was indeed a simple CSS issue I solved by adding .TransactionAmount { color: #FF0000; } .TransactionAmount.green { color: #33FF3C; } in my CSS (replacing the # with a dot)
In the end, @Whitnail provided a much better way to achieve the same result without using JS at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.