Hiding a form-group with Flask Jinja2 and WTForms

旧城冷巷雨未停 提交于 2019-12-10 10:52:38

问题


I'm trying to show or hide a form field based on the state of a checkbox in another part of the form. I thought that I could do this with jQuery .show() or .hide() with relative ease, but I'm not having much luck so far. Any thoughts?

The form class:

class MyForm(Form):
    checked = BooleanField('Check this box:')
    date = DateField('Date:', format='%Y-%m-%d', id="dates")
    submit = SubmitField('Submit')

The template:

{% import "bootstrap/wtf.html" as wtf %}

{% block content %}

{{ form.hidden_tag() }}
{{ wtf.form_field(form.checked) }}
{{ wtf.form_field(form.date) }}
{{ wtf.form_field(form.submit) }}

{% endblock %}

{% block scripts %}

<script type="text/javascript">
jQuery(document).ready(function() {
  $("#checked").change(function() {
    if(this.checked) {
        $('#dates').show();
    } else {
      $('#dates').hide();
    }
  });
});
</script>

{% endblock %}

回答1:


It looks like you are using Flask-Bootstrap.

First, make sure you include {% extends 'bootstrap/base.html' %} in your template. Without that line, you'll lose out on everything Flask-Bootstrap includes in the template, such as jQuery.

Second, you are overriding the scripts block. This is where Flask-Bootstrap includes jQuery. In order to put your own stuff there without losing the base version, you need to use Jinja's super function. It will include the parent template's scripts block along with your own.

After making these changes your template should look something like

{% extends 'bootstrap/base.html' %}

{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
    <form>
        {{ form.hidden_tag() }}
        {{ wtf.form_field(form.checked) }}
        {{ wtf.form_field(form.date) }}
        {{ wtf.form_field(form.submit) }}
    </form>
{% endblock %}

{% block scripts %}
    {{ super() }}

    <script>
        jQuery(document).ready(function() {
            $("#checked").change(function() {
                if (this.checked) {
                    $('#dates').show();
                } else {
                    $('#dates').hide();
                }
            });
        });
    </script>
{% endblock %}


来源:https://stackoverflow.com/questions/27071284/hiding-a-form-group-with-flask-jinja2-and-wtforms

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