首页 > 解决方案 > 使用 JavaScript 的密码可见性

问题描述

我正在尝试检查该复选框是否被选中,如果是,那么它将显示密码。

这是我的代码

登录.html

     
    <div class="form-check">
          {{form.show_pass(class="form-check-input")}}
          {{form.show_pass.label(class="form-check-label")}}
                  <script>
                        
                        var x = document.getElementById('{{form.password.id}}');
                        var checkbox  = document.getElementById('{{form.show_pass.id}}');
                        if (checkbox.checked=='true')
                        {   
                            x.type = 'text'; 
                        }
                    </script>                                   
                </div>

表格.py

      class LoginForm(FlaskForm):

            email = StringField('Email',
            validators=[DataRequired(), Email()])
            password = PasswordField('Password',validators=[DataRequired()],id='pass') 
            remember = BooleanField('Remember Me')
            show_pass = BooleanField('Show Password',id='show')
    
            submit = SubmitField('Login')

标签: javascript

解决方案


只需在页面加载后为显示密码元素添加一个事件侦听器:

window.addEventListener("load", function(){
        var checkbox  = document.getElementById('passwordCheckbox');
        var x = document.getElementById('password');
        checkbox.addEventListener('change', function() {
            if(this.checked) {
                x.type = 'text'; 
            } else {
                x.type = 'password'; 
            }
        });
    });
<input type="checkbox" id="passwordCheckbox" /> Show Password
<br /><br />
<input type="password" id="password" />


推荐阅读