I have a simple Flask application which requires the user to select an option from the dropdown menu of 5 options. This selection is then submitted, run through a pickled model, and produces a prediction.
I would like the most recent option selected by the user to remain selected in the menu after the form is submitted. I'll post my flask application python script and my attempt to coerce this behavior in my .html files. Note that no errors are generated- the application runs, but these portions of javascript have no effect.
I would be so grateful if someone could help me fix the code- I'm a javascript novice, so I wonder if it's rather simple.
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>