Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value and adjust the CSS class for that particular data cell. Currently, I can only alter the entire column data to utilize the Bootstrap class "bg-danger" but not individual cells.

Below is a simplified snippet of the Python code:

import os
import logging

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_table import Table, Col

app = Flask(__name__)
bootstrap = Bootstrap(app)
moment = Moment(app)

class damLevel(object):
    def __init__(self, Dam, PercentFull):
        self.Dam = Dam
        self.PercentFull = PercentFull

class damTable(Table):
    classes = ['table', 'table-bordered', 'table-striped']
    Dam = Col('Dam')
    PercentFull = Col(name='PercentFull', attr='PercentFull', td_html_attrs={'class':'bg-danger'})

@app.route('/', methods=['GET'])
def index():
    
    damData = [damLevel('Boulder', '85'),
               damLevel('FishPond', '7')]

    damForm = damTable(damData)

    return render_template('damlevels.html', damForm=damForm)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))

Here is an example of the HTML template:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}DamLevels{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Dam Levels</h1>
</div>
<div class="container" >
    <form action="" method="get" class="form" role="form">
        <div class="row" style="width:32em">
            {{ damForm }}
        </div>
        <div class="row">
            <a href="/">Return</a>
        </div>
    </form>
</div>
{% endblock %}

Answer №1

I successfully implemented this solution by using iteration in Jinja2 as shown below:

import os
import logging

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_table import Table, Col
from flask_wtf import FlaskForm

app = Flask(__name__)
bootstrap = Bootstrap(app)
moment = Moment(app)
app.config['SECRET_KEY'] = 'NobodyCanGuessThisKey'


class damLevel(object):
    def __init__(self, Dam, PercentFull):
        self.Dam = Dam
        self.PercentFull = PercentFull

class damTable(Table):
    classes = ['table', 'table-bordered', 'table-striped']
    Dam = Col('Dam')
    PercentFull = Col('PercentFull')

@app.route('/', methods=['GET'])
def index():

    damData = [damLevel('Boulder', '85'),
             damLevel('FishPond', '7')]

    damForm=damTable(damData)
    
    print ("damForm type :",type(damData))

    return render_template('damlevels.html', form=damData)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))

HTML Template:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}DamLevels{% endblock %}

{% block page_content %}
  <table id="data" class="table table-striped" style="width:16em">
    <thead>
      <tr>
        <th>Dam</th>
        <th class="text-right">PercentFull</th>
      </tr>
    </thead>
    <tbody>
      {% for damItem in form %}
        <tr>
          <td>{{ damItem.Dam }}</td>
          <td>
            {% set number = damItem.PercentFull | float %}
            {% if number < 25.0 -%}
                <p class="bg-danger text-right">{{ damItem.PercentFull }}</p>
            {% else -%}
                <p class="text-right">{{ damItem.PercentFull }}</p>
            {% endif %}
          </td>
        </tr>
      {% endfor %}
    </tbody>
  </table>

{% endblock %}

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

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

The outerHeight of Elements measured in pixels

Is there a way to increase the outerHeight() function by adding extra pixels? Let's say we have a variable storing the outerHeight of .pg-sect: var $section = $('.pg-sect').outerHeight(); Now, if I want to add an additional 70px to the he ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...

Error: Unrecognized error encountered while using Angularjs/Ionic: Property 'then' cannot be read as it is undefined

codes: js: angular.module('starter.services', ['ngResource']) .factory('GetMainMenu',['$http','$q','$cacheFactory',function($http,$q,$cacheFactory) { var methodStr = 'JSONP' ...

Learn the steps for assigning a distribution tag to an npm package within a private registry

Operating with my own exclusive Gemfury repository, I am actively releasing npm packages. Intrigued by the prospect of applying distribution tags to my packages (as per this guide: https://docs.npmjs.com/cli/dist-tag). The configuration of my npm registr ...

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

Here is a guide on how to develop a PHP function that interacts with a textarea to display text in the specified color by using syntax like [color:red]

Is it possible to code a PHP function that can work alongside a textarea to display text in the specified color by using a syntax like [color:red]? This function operates in a similar manner to Facebook's @[profile_id:0] feature. ...

Implementation of async operations using while loop in Node.js

I'm facing an issue with my code snippet. Here's what it looks like: Rating.find({user: b}, function(err,rating) { var covariance=0; var standardU=0; var standardV=0; while (rating.length>0){ conso ...

When my route in NextJS processes the request, it returns a ReadableStream from req

I am encountering an issue with my code and I have tried looking for solutions in other similar questions without any success. Is there anyone who can assist me? Here is the content of my route.js file: import dbConnect from "@/lib/dbConnect"; i ...

Issue with printing JavaScript value using Selenium_ASSUME_WE_NOT have any changes in the content

I'm currently running tests with Selenium and Java. I've experienced success in printing the pages' HTML from JavaScript by using an alert: js.executeScript("alert($('html').html());"); However, when trying to use return, nothing ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

How can we use JavaScript to retrieve an element with custom styling?

I've encountered a strange issue with my script where it seems to stack up borders and display a 2px border instead of the intended 1px border when switching elements on click. Here is the link code I am using: <li ><a href="plumbing.php"&g ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...