简体   繁体   中英

How to keep dropdown value in the selected field after form submitted using html and js with flask

Upon submitting my form, it also shows the first option value rather than the one just submitted. I'm creating a stock interface and want users to see their selected stock from the dropdown rather than the first when the information comes up. In other words, the correct information appears on the page upon submission but the dropdown field still shows the first dropdown option, not the one the user selected. I am writing this with the flask framework so some of the code appears as such.

        <form class="select_form" method="POST" action="{{ url_for('index') }}">
        <div class="select_ticker">
          <div class="ticker_options">
              <span class="input_selects">Please select</span>
                  <select name="symbol_select" class="symbol_select" id="ticker">
                    {% for symbol in symbols %}
                    <option>
                        {{symbol['symbol']}}
                    </option>
                    {% endfor %}
                  </select>
          </div>
          <button type="submit" class="btn">Go</button>
        </div>
      </form>
      

This is actually a html question.

<form class="select_form" method="POST" action="{{ url_for('index') }}">
    <div class="select_ticker">
      <div class="ticker_options">
          <span class="input_selects">Please select</span>
          <select name="symbol_select" class="symbol_select" id="ticker">
            {% for symbol in symbols %}
            <option {{'selected="selected"' if symbol['selected'] else ''}}>
                {{symbol['symbol']}}
            </option>
            {% endfor %}
          </select>
      </div>
      <button type="submit" class="btn">Go</button>
    </div>
  </form>

Add {{'selected="selected"' if symbol['selected'] else ''}} on <option> , and pass if it is selected in return

@app.route('/index', methods=['GET', 'POST'])
def home():
    symbols=[
        {"symbol": "1", "selected": False},
        {"symbol": "2", "selected": False},
        {"symbol": "3", "selected": False},
        {"symbol": "4", "selected": False},
    ]
    symbol_select = request.form.get('symbol_select')
    for sysmbol in symbols:
        if symbol['symbol'] == symbol_select:
            symbol['selected'] == True
            break
    return render_template("index.html", symbols=symbols)

Similar question can be seen here . And more info for option tag can be seen here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM