问题
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