Изменение JavaScript для поддержания выбора выпадающего меню HTML во Flask - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть простое приложение Flask, которое требует, чтобы пользователь выбрал опцию из выпадающего меню из 5 опций.Затем этот выбор передается, проходит через маринованную модель и создает прогноз.

Я бы хотел, чтобы самый последний вариант, выбранный пользователем, оставался выбранным в меню после отправки формы.Я опубликую свой скрипт Python для приложения фляги и мою попытку принудить это поведение в моих файлах .html.Обратите внимание, что ошибки не генерируются - приложение работает, но эти части javascript не имеют никакого эффекта.

Я был бы очень признателен, если бы кто-то мог помочь мне исправить код - я новичок в javascript, поэтому мне интересноесли это довольно просто.

app.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()

landing_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>

1 Ответ

1 голос
/ 26 сентября 2019

Похоже, что часть сохранения 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
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...