1

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!

2
  • does this help stackoverflow.com/questions/45877080/… ? Commented Apr 24, 2023 at 12:42
  • Thanks for responding to this. I tried this solution but it actually gives an output not what I would like - Imagine the square brackets as the dropdown button here - [{{colours}}]
    – Subham
    Commented Apr 25, 2023 at 4:17

1 Answer 1

1

Since you're using flask, take advantage of the jinja template to fill the dropdwon / select. first send a list to the template rather than a json string. loop over the items and write the template. here is your modified code.

from flask import Flask, render_template, json
app = Flask(__name__)

@app.route('/')
def index():    
    name = ['Red', 'Blue', 'Orange', 'Yellow', 'Green']
    return render_template('index2.html', name=name)

if __name__ == "__main__":
    app.run(debug=True, use_reloader=False)

And here is the template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Report Generation</title>
</head>
<body> 

    <select id="selectvalue">
        {% for n in name %}
            <option value="{{n}}">{{ n }}</option>
        {% endfor %}

    </select>  

</body>
</html>

if you want to send the value back, you have to use a form and call a post route with the selected value. This also can be done using the jinja2 template and a flask route.

3
  • Thanks for responding. Although I had tried your solution at first but the dropdown isn't the way I want. Output looks like this, Imagine the square brackets are dropdown button and within that you have this: [{{n}}]
    – Subham
    Commented Apr 25, 2023 at 4:12
  • Just copy and paste the code as it is. It is running on my side.
    – Elie Saad
    Commented Apr 25, 2023 at 9:11
  • Not working for me. I cleared the cache, tried different browsers and incognito mode as well :(
    – Subham
    Commented Apr 25, 2023 at 10:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.