How to access WTForm fields in JQuery?

我与影子孤独终老i 提交于 2019-12-13 00:27:36

问题


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:

{% 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 -%}

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();
    }

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


回答1:


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();
   }
}


来源:https://stackoverflow.com/questions/29964306/how-to-access-wtform-fields-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!