Search code examples
pythonhtmlflaskjinja2

make dynamic checkmark sign in python


I would like to apply little project, where color of checkmark changes according condition, let us consider following schreenshot : checkmark

definitely i change color of check mark from span tag right? but let us suppose i would like to make it depend on some conditions and i would like to use python for it, namely flask,let us consider following form : age and weight

so user is entering his age and weight and if both of them satisfies some condition, then color of checkmark must be green else it must be red, i know that checkmark sign is this :

<span style="color: rgb(0,255,0);">&#10003 </span><br>

but how to make it dynamic? i have tried following one :i have created text_color variable in python : color_text = "color: rgb(255,255,0);" and apply it in html file like this : &#10003

but does not affect it directly , so how can i do it better? please help me, i will post html and python codes :

python code :

import numpy as np
from flask import Flask, request, jsonify, render_template, send_from_directory

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("Ages.html")


@app.route("/predict", methods=["POST"])
# @app.route('/')
def predict():
    text = [x for x in request.form.values()]
    age = float(text[0])
    weight = float(text[1])
    if age > 18 and weight > 70:
        Text = f"your age is {age} and your  weight is {weight}"
    else:
        Text = f"sorry your age  and weight does not meet  condtions"
    color_text = "color: rgb(255,255,0);"
    # text=list(text)
    return render_template("Ages.html", prediction_text=Text)
    # sentiment_pipeline = pipeline("sentiment-analysis")
    # result =sentiment_pipeline(text)[0]
    # if result['label']=='POSITIVE':
    #     return render_template('Commenting.html',prediction_text=f'emotion of comment is positive')
    # else:
    #     return render_template('Commenting.html', prediction_text=f'emotion of comment is not positive')


if __name__ == "__main__":
    app.run()

html code :

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Enter Your Age</title>
</head>

<body>
  <p>Enter your Age and Weight</p>

  <form action="{{ url_for('predict')}}" method="post">
    <label for="age">enter your age:</label><br><span style={{color_text}}>&#10003 </span><br>
    <input type="text" id="age" name="age" value=""><br>
    <label for="weight">Enter your weight:</label><br><span style={{color_text}}>&#10003 </span><br>
    <input type="text" id="weight" name="weight" value=""><br>
    <input type="submit" value="Submit">
  </form>
  <h4 style="color:Violet;">
    {{ prediction_text }}
  </h4>

</body>

</html>

Solution

  • There are 2 ways to achieve validation in forms:

    • simple html validation, no request is necessary
    • backend validation, an ajax request is necessary

    Depending on your requirements, whether your validation is a complex one or a simple one (in your example I don't see any complicated logic to use an ajax request), you will incorporate one or both methods into your forms.

    The simple example:

    const ageInput = document.getElementById("age");
    const checkmark = document.querySelector(".checkmark");
    
    ageInput.addEventListener("input", function () {
      if (this.value >= 18 && this.value <= 100) {
        checkmark.style.color = "green";
      } else {
        checkmark.style.color = "red";
      }
    });
    <h1>Enter age</h1>
    <form>
      <div>
        <label for="age">Age:</label>
        <input type="text" id="age" required>
        <span class="checkmark" style="color: red;">&#10003;</span>
      </div>
      <button type="submit">Submit</button>
    </form>

    The complex example will require you to write a validation view and instead of using render_template, you need to return a json response. You need to handle it accordingly afterwards. (Flask serializes dictionaries into json.)

    @app.route("/predict", methods=["POST"])
    def predict():
        # some validation steps
        return {"success": True}