Emil Haas
Emil Haas

Reputation: 734

html form select dynamically preselected value (flask)

I have quite simple application written in flask. On the main page I have a form where you select some settings from few dropdown selects. Sth like this:

    <form action="/" method="post">
        Choose year:
        <div class="form-group">
            <select class="form-control" id="year" name="year">
                    <option value='years' selected>years</option>
                    <option value='quarters' >quarters</option>
                {% for year in years %}
                    <option value={{year}}>{{year}}</option>
                {% endfor %}
            </select>
        </div>        
            <div class="form-group">
            <button class="btn btn-default" type="submit">Show statistics</button>
        </div>
    </form>

One of values is preselected now. However, when I choose a different setting, click submit and render the page again (according to the new settings), I would like to have as preselected not the value that was preselected at the first but the value I have chosen. What is the proper way to do this?

Upvotes: 1

Views: 857

Answers (1)

Simeon Nedkov
Simeon Nedkov

Reputation: 1094

Use an {% if %} statement to decide which option should be selected.

<select class="form-control" id="year" name="year">
    <option value='years' {% if choice == 'years' %} selected {% endif %}>years</option>
    <option value='quarters' {% if choice == 'quarters' %} selected {% endif %}>quarters</option>

    ...
</select>

where choice is a variable you pass to the template that holds the value you chose when you submitted the form.

Upvotes: 2

Related Questions