0

I have a small app with a flask backend and jinja2 templating.

In the html, I have a loop that organizes into batches creating 3 columns on the page:

    {% for batch in df.iterrows() | batch(3) %}
      <div class="row">
        {% for row_id, row in batch %}

I have some jQuery to get the item that is clicked on in a cascading dropdown. A jinja2 loop is populating the dropdown by looping through a dataframe. The jQuery is getting the value from the html by ID (as the ul id):

 <ul id="model1" class="list-group">

Ultimately I need three values, one for each batch. However, the code only returns the most recent item clicked on. The reason for that is I can't figure out how to get jQuery to get one item per batch -- or link to the batch somehow. Can I put the batch number in the ul id somehow?

$(document).ready(function(){
  $('ul#menu li').hover(function(){
     $(this).children('ul').delay(20).slideDown(200);
  }, function(){
     $(this).children('ul').delay(20).slideUp(200);
  });

  $('#model1 li').on("click", function(e){
    e.stopPropagation();
    e.preventDefault();
    console.log('model1 ' + e.target.getAttribute('data-val'))
    $("input[name=suggestion1]").val(e.target.getAttribute('data-val'));
  });

//CODE is past here DOESN'T work but I left it in to give an idea

  $('#model2 li').on("click", function(e){
    e.stopPropagation();
    e.preventDefault();
    console.log('model2 ' + e.target.getAttribute('data-val'))
    $("input[name=suggestion2]").val(e.target.getAttribute('data-val'));

  });
  $('#model3 li').on("click", function(e){
    e.stopPropagation();
    e.preventDefault();
    console.log('model3 ' + e.target.getAttribute('data-val'))
    $("input[name=suggestion3]").val(e.target.getAttribute('data-val'));
  });

  $("form").submit(function(){
    var s1 = $("input[name=suggestion1]").val();
    var s2 = $("input[name=suggestion2]").val();
    var s3 = $("input[name=suggestion3]").val();
    console.log(s1, s2, s3);
  });
});
zelda26
  • 489
  • 2
  • 10
  • 33

1 Answers1

0

Posting this in case it helps someone else.

This excellent post explains how to use the loop variable in a flask template: count number of rows in flask templates

For my code, I made the div ID change based on the loop index.

{% for batch in recomm_df.iterrows() | batch(3) %}
     <div class="row">
      {% for row_id, row in batch %}
       <div class="col-md-4" id="cat_{{loop.index}}">

Within that loop, I gave my unordered list an ID like :

<ul id="cat_sug" class="list-group">

Then you can grab those the data val that is clicked on in JQuery:

  $('#cat_1 #cat_sug').on("click", function(e){
    e.stopPropagation();
    e.preventDefault();
    console.log('cat_1 ' + e.target.getAttribute('data-val'))
    // var s1 = e.target.getAttribute('data-val');
    $("input[name=suggestion1]").val(e.target.getAttribute('data-val'));
  });
zelda26
  • 489
  • 2
  • 10
  • 33