I started reading into some flask application programming and I have been trying to get drop down menu to work, but so far I have had no luck. What I want to do is, when the use
You need to use Ajax here to retrieve a list of the food depending on your choice of foodkind. So in your template you will need to include something like this:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function() {
$('#foodkind').change(function() {
var foodkind = $('#foodkind').val();
// Make Ajax Request and expect JSON-encoded data
$.getJSON(
'/get_food' + '/' + foodkind,
function(data) {
// Remove old options
$('#food').find('option').remove();
// Add new items
$.each(data, function(key, val) {
var option_item = '<option value="' + val + '">' + val + '</option>'
$('#food').append(option_item);
});
}
);
});
});
</script>
</head>
<body>
<form>
{{ form.foodkind() }}
{{ form.food() }}
</form>
</body>
</html>
This code will make a shorthand Ajax request for JSON-encoded data. This data contains a list of the values for your food select box.
For this to work you will need to add an endpoint /get_food/<foodkind>
to your Flask views:
food = {
'fruit': ['apple', 'banana', 'cherry'],
'vegetables': ['onion', 'cucumber'],
'meat': ['sausage', 'beef'],
}
@app.route('/get_food/<foodkind>')
def get_food(foodkind):
if foodkind not in food:
return jsonify([])
else:
return jsonify(food[foodkind])