首页 > 解决方案 > 修改 javascript 以维护 Flask 中的 HTML 下拉菜单选择

问题描述

我有一个简单的 Flask 应用程序,它要求用户从 5 个选项的下拉菜单中选择一个选项。然后提交此选择,通过腌制模型运行,并产生预测。

我希望用户选择的最新选项在提交表单后在菜单中保持选中状态。我将发布我的烧瓶应用程序 python 脚本,并尝试在我的 .html 文件中强制执行此行为。请注意,不会生成任何错误 - 应用程序运行,但这些部分的 javascript 无效。

如果有人可以帮助我修复代码,我将不胜感激-我是 javascript 新手,所以我想知道它是否相当简单。

应用程序.py

from flask import Flask, request, render_template
import pickle
import numpy as np

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('landing_ex_2.html')

@app.route('/resell', methods=['POST'])
def get_price():
    if request.method=='POST':
        result=request.form
        category = result['category']

        pkl_file = open('cat', 'rb')
        index_dict = pickle.load(pkl_file)
        cat_vector = np.zeros(len(index_dict))

        try:
            cat_vector[index_dict['category_'+str(category)]] = 1
        except:
            pass

        pkl_file = open('model.pkl', 'rb')
        model = pickle.load(pkl_file)
        prediction = model.predict(cat_vector.reshape(1, -1))

        return render_template('landing_ex_2.html', prediction=prediction)

if __name__ == '__main__':
    app.debug = True
    app.run()

登陆_ex.html:

<!DOCTYPE html>
<html>
<head>

  <!-- Form -->
  <h3>
  <form id = "selling_form" action = "/resell" method="POST">
    <p> Select Category :   
        <select id = "mySelect" name="category">
        <option value="tops">Tops (shirts, blouses, tank tops) </option>
                <option value="bottoms">Bottoms (pants, shorts, skirts) </option>
                <option value="dresses">Dresses </option>
                <option value="outerwear">Outerwear (jackets, sweaters) </option>
                <option value="accessories">Accessories (small miscellaneous items) </option>
    </select>

    <p> <input type ="submit" value="submit" /> </p>
        </h3>

<script>
//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
  //to set the selected value:
  document.getElementById("mySelect").value = sessionStorage.getItem("selectedOption");
}

//this will set the value to sessionStorage only when user clicks submit
document.getElementById("selling_form").addEventListener("submit", () => {
  //to get the selected value:
  var selectedOption = document.getElementById("mySelect").value;
  sessionStorage.setItem("selectedOption", selectedOption);
});

</script>

  <!-- Output -->
      <p> 
      <h2> Your sale prediction is {{ prediction }}</h2>
      </p>

</body>
</html>

标签: javascripthtmlflaskdrop-down-menu

解决方案


看起来JS保存和设置选择选项的部分是错误的。您始终存储并设置"tops"选择元素本身的值而不是选择选项。

尝试存储选定的项目索引:

//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
  //to set the selected value:
  var select = document.getElementById("mySelect");
  select.selectedIndex = sessionStorage.getItem("selectedOption"); // set index of selected element
}

//this will set the value to sessionStorage only when user clicks submit
document.getElementById("selling_form").addEventListener("submit", () => {
  //to get the selected value:
  var select = document.getElementById("mySelect");
  sessionStorage.setItem("selectedOption", select.selectedIndex); // store index of selected element
});

推荐阅读