如何访问JQuery中的WTForm字段? [英] How to access WTForm fields in JQuery?

查看:58
本文介绍了如何访问JQuery中的WTForm字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Flask建立一个网站,并且正在将WTForms用于注册页面,如下所示:

I'm trying to make a website with Flask and am using WTForms for a registration page like so:

views.py:

@app.route('/register', methods=('GET', 'POST'))
def register():

    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(form.password.data)
        form.populate_obj(user)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        return redirect(url_for('index'))
    return render_template('register.html', title='Register', form=form, user=current_user)

register.html:

register.html:

{% extends "base.html" %}
{%- block content -%}
{% import "formhelpers.html" as fields %}
<div id="login_container">
    <div id="register_title"><p>Register</p></div>
    <form method="post" action="{{ url_for('register') }}">
        {{ form.hidden_tag() }}
        {{ fields.render(form.first_name, placeholder="Firstname") }} <br/>
        {{ fields.render(form.last_name, placeholder="Surname") }} <br/>
        {{ fields.render(form.email, placeholder="Your email") }} <br/>
        {{ fields.render(form.password, placeholder="Password") }} <br/>
        {{ fields.render(form.confirm, placeholder="Confirm password") }} <br/>
      <p>
      <input class="btn" type="submit" value="register"></a>
      </p>
    </form>
</div>

{%-endblock-%}

{%- endblock -%}

我想做的是,如果用户输入的密码不匹配,则向他们显示错误消息 .我了解您可以在jquery中执行以下操作:

What I want to do is give the user an error message as they type if their passwords do not match. I understand that you can do something like this in jquery like this:

$('.password-field').keyup(function() {
    var p1 = $(this).val();
    var p2 = $(.confirm-field).val();
    if (p1 != p2) {
        $('.error-message').show();
    }

但是我不确定如何访问JQuery中的WTForm字段.有什么想法吗?

But I am not sure how to access the WTForm fields in JQuery. Any ideas?

推荐答案

这可行,因为我们拥有呈现的HTML/表单字段,可以帮助您编写更简单的代码.

This could work, is we had the rendered HTML/form-fields we could help you with easier code.

var p1 = $("#login_container input[type=password]:nth-child(1)");
var p2 = $("#login_container input[type=password]:nth-child(2)");
$(p1).keyup(function() {
   if ($(p1).val() != $(p2).val()) {
      $('.error-message').show();
   }
}

这篇关于如何访问JQuery中的WTForm字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆