Flask Dynamic dependent dropdown list

15,729

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])
Share:
15,729
ben
Author by

ben

Updated on June 15, 2022

Comments

  • ben
    ben almost 2 years

    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 user selects a Type of Food from the first dropdown list, it should get the corresponding list from the database and fill the second set of drop down list. I do not know how to make it send a quick request once a selection is made. I really don't understand what should be done here.

    <body>
      <div>
        <form action="{{ url_for('test') }}" method="POST">
          <div>
            <label>Food:</label>
            <select id="food" name="food" width="600px">
            <option SELECTED value='0'>Choose your fav food</option>  
            {% for x in food %}
              <option value= '{{ x }}'>{{x}}</option>
            {% endfor %}
          </select>
            <!-- After a selection is made, i want it to go back to the database and fectch the results for the below drop box based on above selection -->
          </div>
          <div>
            <label>Choose Kind of Food:</label>
            <select id="foodChoice" name="foodChoice" width="600px">
            <option selected value='0'>Choose a kind</option>
            {% for x in foodChoice %}
              <option value= '{{ x }}'>{{x}}</option>
            {% endfor %}
          </select>
          </div>
          <div>
            <input type="submit">
          </div>
        </form>
      </div>

    app.html

    @app.route('/', method = ['GET', 'POST'])
    def index():
        foodList = [ i.type for i in db.session.query(FoodType)]
        return render_template('main.html', food=foodList)
    
    @app.route(/foodkind', method = ['GET', 'POST'])
    def foodkind():
            selection = request.form['foodChoice']
            foodKind = [ i.kind for i in db.session.query(FoodType).filter(FoodKind == selection)]
            return render_template('main.html', foodChoice = foodKind)
    

    I have looked at many questions and I have not yet found anything simple that would help me. It would be great if someone can demo a code for me so I can look and learn from it.