Reputation: 945
I have a Flask backend with MySQL and need to pull values from a table to display in a dropdown.
I have a table with single values like Banana, Apple, Orange, etc.
Inside my html code, the option shows up if a user selects another dropdown (which is hard-coded) so the code looks like this:
$(function() {
$("#inputType").change(function() {
var myform = "<div id=\"newForm\">"
+"<label for=\"inputFruit\">Fruit:</label>"
+"<select class=\"form-control\" id=\"inputFruit\" required>"
+"<option></option>"
+"</select>"
if ($("#inputType").val() == "fruits") {
$(myform).insertBefore("#btnSignUp");
} else {
$("#newForm").remove();
}
Inside my flask app:
@app.route('/getFruits') # gets my fruits as a list and returns
Where do I add code so that the values I get from /getFruits is put into the option in the HTML?
Upvotes: 0
Views: 2457
Reputation: 6556
You can pass the context data (fruits list) into javascript code of your template, use JSON will meet your requirement:
Your View:
import json
@app.route('/getFruits')
def my_view():
data = ['Banana', 'Apple', 'Orange', 'Pear', 'Watermalon'] # you can get list from your DB instead
return render_template('yourtemplate.html', data=json.dumps(data))
Your Template:
$(function() {
$("#inputType").change(function() {
var myform = "<div id=\"newForm\">"
+"<label for=\"inputFruit\">Fruit:</label>"
+"<select class=\"form-control\" id=\"inputFruit\" required>"
{% for item in data %}
+"<option>{{ item|safe }}</option>"
{% endfor %}
+"</select>"
if ($("#inputType").val() == "fruits") {
$(myform).insertBefore("#btnSignUp");
} else {
$("#newForm").remove();
}
Upvotes: 1