Search code examples
javascripthtmlflaskonclicklistenerdynamic-tables

How to fetch contents of clicked cell in a dynamic table using javascript


I have tables present. Now if I click any of the below table names, like feedback, how can I get the values for them. table is dynamic. Below is code for displaying table names.

<table class="table  table-hover" style="margin-top: 25px;width:300px;">
  <thead>
    {% for i in tables %}
    <tr>
      <th > {{ i }} </th>
    </tr>
      {% endfor %}
  </thead>
</table>

Note, i is value of table name.

Here I want to add 2 things:

  1. A click listener
  2. Get the values by clicking on the tables using JavaScript

Solution

  • To get the element clicked, you can listen for click events on the table, then use the event.target property to get the element that was clicked.

    // set up the 'click' event listener
    myTable.addEventListener('click', event => {
      const clickedElement = event.target;
    
      // now that you have the clicked element, do what you want with it
      let stuffIWant = clickedElement.<some method or property of element>;
    });
    

    From the example in the question, it appears that you looking for the contents of a <th> element. If that's the case, you can use:

    stuffIWant = clickedElement.innerText;
    

    A working example:

    // listen for all 'click' events within table
    const tbl = document.getElementById('tbl');
    tbl.addEventListener('click', event => {
      const el = event.target;
      alert(`you clicked "${el.innerText}"`);
    });
    #tbl {
      background-color: #aaa;
      margin: 12px;
    }
    th {
      padding: 0.5rem 2rem;
      border: 1px solid #999;
    }
    /* change cursor to hand on hover */
    th:hover {
      cursor: pointer;
    }
    <table id="tbl">
      <thead>
        <tr><th>Feedback</th></tr>
        <tr><th>Complaint</th></tr>
        <tr><th>Praise</th></tr>
      </thead>
    </table>