Javascript Onclick with Table Rows

javascript

To add an onclick event to table rows in JavaScript, you can use the addEventListener method to attach an event listener to each row in the table. Here’s an example:

<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Smith</td>
      <td>[email protected]</td>
      <td>555-1234</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
      <td>[email protected]</td>
      <td>555-5678</td>
    </tr>
  </tbody>
</table>

<script>
  var table = document.getElementById('myTable');
  var rows = table.getElementsByTagName('tr');

  for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener('click', function() {
      // Do something when a row is clicked
      console.log('Row clicked: ' + this.cells[0].textContent);
    });
  }
</script>

In this example, we first get a reference to the table using getElementById. We then get all the rows in the table using getElementsByTagName(‘tr’). We iterate through each row using a for loop and attach an onclick event listener to each row using addEventListener.

When a row is clicked, the event listener function is called and the this keyword refers to the clicked row. In this example, we simply log the text content of the first cell in the row to the console.

You can modify the event listener function to perform any action you want when a row is clicked, such as highlighting the row or displaying additional information.