pythonbootstrap-5flask-wtformswtforms

Submit wtforms-Form with DateField on selecting a date


I want to build a webpage using bootstrap 5 and flask-wtforms (python 3.11). I have a Form with a Datepicker and when I choose a date I want to submit the Form. For now I have a submitField(/Button) and that works fine, but I'd prefer it if it was instant without clicking a button.

This is the class I use for the form in python:

class DateForm(FlaskForm):
    datum = DateField('Datum', validators=[DataRequired()])
    nurabwmabanz = BooleanField('nur abwesende Mitarbeiter anzeigen')
    submit = SubmitField('Aktualisieren')

This is the part of the html code belonging to the form:

    <form method="POST" action="">
        {{ form.hidden_tag() }}
        <a role="button" class="btn btn-outline-info float-start me-1 mt-4 pt-3 pb-3" href="{{ url_for('abwesenheitslistebase') }}">h</a>
        {{ form.submit(class="btn btn-outline-info me-3 float-end mt-4 pt-3 pb-3") }}
        <fieldset class="form-group">
            <div class="form-group col-3">
                {{ form.datum.label(class="form-control-label mt-1 ms-2") }}
                {% if form.datum.errors %}
                    {{ form.datum(class="form-control form-control-lg is-invalid") }}
                    <div class="invalid-feedback">
                        {% for error in form.datum.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ form.datum(class="form-control form-control-lg col-1", value=abwdatum) }}
                {% endif %}
            </div>
        </fieldset>
            <div>
                {{ form.nurabwmabanz(checked=cbnurabwmabanz) }}{{ form.nurabwmabanz.label(class="form-control-label mt-1 ms-2") }}
            </div>
    </form>


Solution

  • add some JavaScript to your Date input:

    class DateForm(FlaskForm):
        datum = DateField('Datum', 
          validators=[DataRequired()], 
          render_kw={"onchange": "this.form.submit()"}
        )
        nurabwmabanz = BooleanField('nur abwesende Mitarbeiter anzeigen')
        submit = SubmitField('Aktualisieren', name="btnSubmit")
    

    If the name of the submit button is "submit" then this.form.submit refers to the submit button and not the submit() method...so you should name it anything other than "submit"