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

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Node.js Express not inserting data with Mongoose when using form data

For the past two weeks, I have been struggling to post data to insert into a database using form-data. It consistently shows a 400 bad request error. Below is my code for server.js: require('./db.js') let express = require('express') ...

An illustration of webpack 4 and Vue.js compatibility tailored specifically for Internet Explorer 11, featuring multiple entry points

This feels like déjà vu - yet another issue with Internet Explorer and webpack. I'm on the brink of deploying my project when IE 11 decides to mess everything up. I thought I had covered all bases with babel-polyfill and the latest versions, but of ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

Strategies for sorting data in d3js/dimplejs visualizations

I am looking to enhance the interactivity and responsiveness of a d3js/dimplejs chart by implementing filtering based on clicks in the legends for different series. The code I tried below did not hide the series as expected, although it worked well with a ...

Retrieve the date from 7 days ago and display it in the format "2015-06-23" using JQuery/JavaScript

Looking to retrieve last week's date in the following format: "2015-06-23", as opposed to "2015-06-16". JavaScript: t = new Date(); // Tue Jun 23 2015 21:00:47 GMT-0700 (PDT) t.toISOString(); // "2015-06-24T04:00:47.955Z" The current date format i ...

Creating a dynamic link in Vue JS is a cinch!

I currently have the following code snippet: <b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100"> <b-dropdown-item @click="selectedFactory='China'"> ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Unable to transform data types

Currently, I am studying the JavaScript for automation session at WWDC. Here is an example taken from slide 99 that I am working on. On a fresh installation of Yosemite, I encountered an error on line 3. Safari = Application('Safari') doc = Safa ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Will the script src onclick change have an effect after the page is fully loaded?

Imagine you have a script that loads right away when a page loads. Now, what happens if the script src changes when you click on a button? Will the new src get executed? Here is some example code: <button> click </button> <script class=" ...

Is there a safe method to convert an HTML attribute (Javascript Object) into an array using Javascript or JQuery?

I have an HTML element containing a javascript object: <div ui-jq="easyPieChart" ui-options="{ percent: 75, lineWidth: 5, trackColor: '#e8eff0', barColor: ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

Insert a 5-second delay in the JavaScript code before triggering the click event on the next button

Currently, I have a JavaScript code in place that is fairly straightforward. The webpage contains about 100 buttons with the class button, and I am successfully simulating clicking each one of them systematically. However, I would like to introduce a dela ...

Switch up row values in an array and transform them into an object using SheetJS

I am struggling to format an array where each "Working Day" is represented as an object with specific details like index and start/end date. I need help manipulating the JSON data to achieve the desired structure. The package I'm currently using is: ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

Creating React elements dynamically with material-ui can be done by utilizing state expressions in properties. This allows for the generation

Within a functional component, I aim to dynamically generate material-ui context menus by utilizing a state object: let legendContextMenuStatesObject = {}; for (let key of keys) { legendContextMenuStatesObject[key] = initialState; } const [lege ...

Is it possible to use AngularJS to show additional information between rows when a table row is clicked in HTML

I'm currently working on an html table where the <tbody> is generated using angular's ng-repeat. Take a look at my html: <tbody ng-repeat="car in carList | filter:tableFilter"> <tr> <td><a target="_blank" h ...

How can you modify a hyperlink URL before it is activated?

I'm facing an issue with a URL structure that needs updating before it is clicked. The current URL looks like this: https://url.com/a b c which is causing redirection problems because the actual link has underscores instead of spaces in its URL. Is ...

Enhancing Bootstrap Slider Range with jQuery/Javascript

Currently, I have incorporated the Bootstrap slider into a webpage that features two sliders on a single page. The range of the second slider depends on the value of the first one. It is crucial for me to be able to update the range of the second slider af ...