I am trying to display a dropdown menu in a flask web application. I pass a python list as an input for the dropdown menu and I want to recieve the selected item back as the output on click of a submit button.
Here's my simple python backend:
from flask import Flask, render_template, json
app = Flask(__name__)
@app.route('/')
def index():
name = json.dumps(['Red', 'Blue', 'Orange', 'Yellow', 'Green'])
return render_template('index2.html', name=name)
if __name__ == "__main__":
app.run(debug=True, use_reloader=False)
And here's the frontend (index2.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Report Generation</title>
</head>
<body>
<select id="selectvalue">
</select>
<script>
var selectvalue = document.getElementById("selectvalue");
// const test = {{ name | tojson | safe }}
const test = JSON.parse("{{name}}");
for (var i=0;i<test.length;i++)
{
var selection = document.createElement('OPTION');
var txt = document.createTextNode(test[i]);
selection.appendChild(txt);
selection.setAttribute("value", test[i]);
selectvalue.insertBefore(selection, selectvalue.lastChild);
}
</script>
</body>
</html>
I tried two methods, the second line (when uncommented) within tag is giving me this error: Uncaught SyntaxError: Unexpected token '{'
and trying the third line gives me this error: Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse ()
Here's the output I want: dropdown
Also, how do I recieve the selected item back to flask backend on click of a button? Thanks in advance!