Home > Software engineering >  How can I add an onClick event listener to a table?
How can I add an onClick event listener to a table?

Time:04-15

I am currently trying to add a feature where when I click the name of a user in the table it will display all of the posts made by that User however I am completely stumped. The url for the posts is https://jsonplaceholder.typicode.com/posts

I currently have the table set up and will attach images of the table and code below.

Here is the problem I am trying to solve for further context

"Using jQuery or vanilla JS you will display each 'USER' in a table. When the user selects a 'USER' in the table, it will display all of the 'POSTS' that were created by that 'USER'."

index.js

index.html

table

data.json

CodePudding user response:

To add a click event handler to a table row with JavaScript, we can loop through each row and set the onclick property of each row to an event handler.

For instance, we add a table by writing:

<table>
  <tbody>
    <tr>
      <td>foo</td>
      <td>bar</td>
    </tr>
    <tr>
      <td>baz</td>
      <td>qux</td>
    </tr>
  </tbody>
</table>

Then we write:

const createClickHandler = (row) => {
  return () => {
    const [cell] = row.getElementsByTagName("td");
    const id = cell.innerHTML;
    console.log(id);
  };
};

const table = document.querySelector("table");
for (const currentRow of table.rows) {
  currentRow.onclick = createClickHandler(currentRow);
}

to add event handlers to each row.

Reference : https://thewebdev.info/2021/09/12/how-to-add-an-click-event-handler-to-a-table-row-with-javascript/#:~:text=Row with JavaScript-,To add an click event handler to a table row,row to an event handler.&text=to add event handlers toe,table row as a parameter.

CodePudding user response:

wrap every user with an 'a' tag with the "onClick" event to each one of them with their id's. hope this will help. (:

  • Related