'Creating clickable table that sends selected row data as a post request to a flask route

Sample code: --------------------Start Code------------------ `

        <tr>
        <th>Year</th>
        <th>Month</th>
        <th>Day</th>
        </tr>
        <tr>
            <td>2000</td>
            <td>January</td>
            <td>24</td>
        </tr>
  </table>

<button type="submit" class="x" formaction="/" formtarget="_blank">send data</button>
`

--------------------End code------------------ I want the user to select a row in the table. And once they select the row the data from the row is sent to a route in my flask application.

Basically the whole row needs to be clickable so maybe the onclick attribute might work?

Example of flask route:

@app.route('/',methods=['POST','DELETE','GET']) def table(): return render_template('table.html')

Thanks so much!



Solution 1:[1]

Put an onclick on each row and get it's child by using getElementByTagsName (how to get a td value of a table using javascript)

Then put a fetch to post the selected data on the route you want to process the data.

HTML


<table>
<tr>
        <th>Year</th>
        <th>Month</th>
        <th>Day</th>
</tr>
<tbody>
<tr onclick = "gen(this)">
            <td>2000</td>
            <td>January</td>
            <td>25</td>
        </tr>
        
<tr onclick = "gen(this)">
            <td>2003</td>
            <td>February</td>
            <td>24</td>
        </tr>        
</tbody>
  </table>

Javascript

<script type="text/javascript" charset="utf-8">
    function gen(e){
  var year = e.getElementsByTagName("td")["0"].innerText
  var month =  e.getElementsByTagName("td")["1"].innerText
  var date = e.getElementsByTagName("td")["2"].innerText
  
 var list = {
   year: year,
   month: month,
   date: date
 }
    
  fetch(`${window.origin}/print`, {
    method: "POST",
    credentials: "include",
    body: JSON.stringify(list),
    cache: "no-cache",
    headers: new Headers({
      "content-type": "application/json"
    })
  })
  

}
  </script>

Python


@app.route("/print", methods = ["post"])
def printer():
  data = request.get_json()
  print(data)
  
  return "hey"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Winmari Manzano