0

I have a form with a SelectField and if a specific option in there is selected I want to show a different field where a user can input more options.

So my form class looks like

class QuestionForm(FlaskForm):
    type = SelectField("Question Type")
    options = SelectField("options", validators=[Optional()])

Then my views\questions.py blueprint renders the form like

def question():
    ...
    form = QuestionCreationForm()
    form.type.choices = [
        (type, type) for type in ["Type 1", "Type 2"]
    ]
    form.options.choices = ["option 1", "option 2"]
    if form.validate_on_submit():
        ...
    else:
        flash_form_errors(form)

    return render_template(
        "question.html",
        form=form,
    )

And finally the html:

{% extends "base.html" %}
{% block page_title %}Questionnaire{% endblock %}
{% block content %}
...
    <form method="POST" action="{{ url_for('questionnaire.questionnaire') }}">
        <div id="type_selection" class="select is-medium is-expanded" onchange="WHAT HERE?">
              {{ form.type }}
        </div>
        <div id="option_selection" class="select is-medium is-expanded DISPLAY NONE HERE?" onchange="WHAT HERE?">
              {{ form.options }}
        </div>
    </form>
....
{% endblock %}
<script>
    function myFunction() {
        // ??
    }
</script>

So my guess is to have an onchange for my typesform field and check if the selected value is let's say Type 2 in order to change the rendering of the optionsfield to be displayed. However, I wasn`t able to stick together all the parts correctly.

This questions is a potential duplicate, but I cannot comment there and the answer provided was not specific enough the help a newby like me. Thanks! Flask WTF forms: can a new field be shown if a user selects a specific choice in SelectMultipleField?

phlprcks
  • 55
  • 1
  • 9

1 Answers1

0

To not make you all fuzzy about the answer on this one. You will need some javascript too. There is pretty straight to the point tutorial on youtube that is no longer than 10 - 15 mins , so search for flask dynamic select field. Hope it will help you out.

dariokl
  • 61
  • 2