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.
- [Django]-Django – 'module' object is not callable
- [Django]-Remove the decimal part of a floating-point number in django?
- [Django]-Django.db.utils.InterfaceError: (0, '')
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
- [Django]-Getting Http403 when saving files through django s3 middleware (but can save using boto in shell)
- [Django]-'web:' is not recognised as an internal or external command
- [Django]-What are the cons of using Django compared to (ASP.net MVC,NHibernate and Spark View Engine)?
- [Django]-Celery not connecting to redis server
- [Django]-Does Django ModelForm set unspecified fields to empty?