Modify appearance of text depending on input (HTML & JS)

I am currently working on building an HTML table using Django. My goal is to dynamically change the color of numbers in the table to red when they are negative and green when they are positive. I understand that JavaScript is required for this functionality, but so far, I have been unsuccessful in implementing it. Any assistance or guidance on how to achieve this would be highly appreciated!

Below is a snippet of my Django HTML template connected 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 have confirmed that the JavaScript code is functional, as I tested it independently of my project. However, despite my efforts, the numbers in my table remain in gray and do not change color as intended. I even substituted {{ transaction.TransactionAmount }} with plain numbers like "1" and "-1", but the issue persists (I also tried removing the gray base color from the CSS without success).

Here is a glimpse of 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;
}

Additionally, here is the Django model I am using:

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

I have a basic understanding of programming, so any support provided will be greatly appreciated. Thank you in advance for your assistance!

Answer №1

When dealing with positive and negative numbers, consider changing the color of the number based on its sign. This can be achieved using JavaScript, although there are alternative methods available. If you're new to programming, you might find it easier to handle this task within the Django template rather than diving into a complex JS solution. If JS is essential for other aspects of your website, the other responses can guide you on fixing the issue.

To improve readability, I have condensed this response. (Remember, having both inline styling and an external CSS file is not recommended!)


<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>

Here's the appropriate CSS styling:

.NegativeTransaction {
  color: #FF0000;
}

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

Answer №2

Your HTML code mistakenly assigns 'TransactionAmount' as a class for the td elements, but in the CSS, it is defined as an ID with rules specified for #TransactionAmount and #TransactionAmount.green. To correct this issue, update the rules to use .TransactionAmount and .TransactionAmount.green instead.

Answer №3

After testing your code, I found that it is working perfectly. The only modification I made was adding the red class.

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

Furthermore, it appears that the CSS for the classes .green and .red may have been overlooked, as it was not included in the CSS code above.

Feel free to check it out on JSFiddle

.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

When the height is set to 100vh, the Div and Image appear misaligned vertically

Could someone explain why there is a vertical separation between the div and the image? <div style="height: 100vh; display: inline-block;width: 50%; background-color: blue">TEST </div><!-- --><img src="photos/openening.jpg" alt="SICK ...

Is there a way to get a Chrome extension to run automatically in the background?

I am looking to develop a custom chrome extension with a countdown timer functionality that automatically runs in the background. However, I am facing an issue where my background.js file is unable to access the popup.html file. How can I execute scripts i ...

Need to double tap to remove item in redux-toolkit

Trying to delete an item in Redux Toolkit, but having trouble as the remove function only works on screen. I have to press twice to delete the previous one. Here is the reducer: const noteReducer = createSlice({ name: "note", initialState: N ...

Save a newly uploaded image to Github utilizing NodeJS and the Github API

Struggling to upload an image to my Github repo using NodeJS and Github API has been a challenge for me. I have managed to create the SHA, Commit Tree, and all necessary steps, but the final hurdle is passing the image to the API and saving it as an actual ...

Managing dynamically loaded scripts in Meteor.js

This poses an interesting query: is there a way to regulate which scripts a client is provided with? I've partitioned my code into dynamically loadable segments using the import('dynamically_loadable_file') method, but each time it's ca ...

Exploring the effects of zooming on YouTube videos in Firefox

Strange phenomenon, but my website appears to be having display issues specifically on Firefox. Surprisingly, it looks perfectly fine on IE9, Safari, and Chrome. The layout of the site in Firefox seems to change when I zoom in or out, resulting in the You ...

There seems to be an issue with configuring placeholders in Tailwind CSS

After deciding to switch to using only tailwind CSS, I noticed that on a particular page there were inputs with transitions but no icon on the inner left side. Adjusting the colors and position of the placeholder helped prevent collisions between the icon ...

What's the best way to handle the output of an HTTP request in my specific situation?

Struggling to pass http request results from parent controller to child controller... This is what I have: <div ng-controller = "parentCtrl"> <button ng-click="callApi()">click me</button> <div ng-controller = "childCtrl"& ...

Retrieve the inner content of parentheses within a string, utilizing recursion for nested parentheses

I am currently working on a function that will extract words enclosed in parentheses and store them in their own array, accounting for nested parentheses recursively. For example, when given the string "((a b) ugh (one two)) pi", I would like it to be tra ...

How to properly implement envMap in Three.js?

Could someone assist me in finding a material similar to the one shown here? I attempted to implement it using the following code: * { margin: 0; padding: 0; } .object { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; pointer-events: no ...

The Django admin panel does not seem to display my app

Here is the code snippet in question: from django.contrib import admin from test_app.models import Master, Detail class DetailInline(admin.TabularInline): model = Detail class MasterAdmin(admin.ModelAdmin): inlines = [DetailInline] admin.reg ...

Utilize Jquery's "find" function to showcase an image

I am attempting to showcase an image using jQuery. I have a function that accepts ID and PATH as parameters. The ID indicates the section (each section is an HTML page that loads upon user action). Additionally, there is a text area where I am displaying t ...

Once the 'add to cart' button is selected, it must remain disabled until the product is deleted from the user's cart page

Embarking on my inaugural web development project, I am utilizing PHP, AJAX, and jQuery. I seek a resolution for the following challenge: Upon a user clicking the 'add to cart' button, that particular product or the button itself should become d ...

I'm having trouble with my code not fitting all screen resolutions. I usually code on a Macbook, but recently switched to a Windows computer and now everything is out of whack

$(function(){ $("#Welcome").typed({ strings: ["PROGRAMMERS / NETWORKERS"], typeSpeed: 60 }); }); html { background-color: mintcream; background-size: 100%; } /* Home */ .homeheader button { background-color: #4CAF450; top: ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Exploring the world of jQuery slide animations and customizing content with the tiny

Implementing tinyMCE in a user interface design with jQuery's .show("slide") animation has posed a challenge for me. The form is structured like a wizard, split into different sections (Biodata, Contact Information, Save) without using next and back b ...

Javascript's event.keyCode does not capture the Backspace or Delete keys in Internet Explorer

Looking to detect when the Backspace and Delete keys are pressed using javascript/jQuery, I have the following code: $("textarea[name=txt]").keypress(function(e){ var keycode = e.keyCode ? e.keyCode : e.which; if(keycode == 8){ // backspace ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Using AngularJS in combination with a Flask backend to visualize the data being sent from the backend

I am currently developing a Single Page Application using Angular with a Python/Flask backend that connects to MongoDB. The challenge I'm facing is that, although I can retrieve data from the backend using a $http get request in Angular as an object ...