How to toggle password visibility while using flask and flask_wtf forms?

Viewed 2159

I just started learning flask, and i was wondering how can I toggle password field visibility by a button added in html and i can't figure it out. app.py

from flask import Flask
from flask import render_template, url_for, flash, redirect
from forms import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '40928745c948f3f1e67703b23b49b9c5'

@app.route('/', methods=('GET', 'POST'))
def home():
    form = MyForm()
    return render_template('home.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

forms.py

from flask_wtf import FlaskForm
from wtforms import PasswordField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
    password = PasswordField('password', validators=[DataRequired()])

home.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Sample</title>
  </head>
  <body>
    <form method="POST" action="/">
  {{ form.hidden_tag() }}
  {{ form.name.label }} {{ form.name(size=20) }}
  <input type="submit" value="Go">
  <button type="button" name="">Show Password</button> <! –– Using this button, toggle password visibilty -- !>
</form>
  </body>
</html>

Now I know that {{ form.hidden_tag() }} is to hide input fields but how do I toggle the visibility?

1 Answers

You can use JavaScript

home.html

window.addEventListener("load", function(){
    var checkbox  = document.getElementById('{{form.check.id}}');
    var x = document.getElementById(''{{form.password.id}}'');
    checkbox.addEventListener('change', function() {
        if(this.checked) {
            x.type = 'text'; 
        } else {
            x.type = 'password'; 
        }
    });
});

forms.py

  class MyForm(FlaskForm):
  password = PasswordField('password', validators=[DataRequired()],id='password')
  show_password = BooleanField('Show password', id='check')
Related