Hiding form group with Flask Jinja2 and WTForms

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

Form class:

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

      

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


source to share


1 answer


It looks like you are using Flask-Bootstrap .

First, make sure you include {% extends 'bootstrap/base.html' %}

in your template. Without this line, you will lose anything that includes a Bootstrap checkbox in a template like jQuery.

Second, you are overlapping the block scripts

. Flask-Bootstrap includes jQuery here. To host your own stuff without losing the base version, you need to use the Jinja functionsuper

. It will include the parent template scripts

as well as your own.



After making these changes, your template should look something like this:

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

      

+1


source







All Articles