0

I am trying to generate a table dynamically with elements I am getting through a fetch, I get to draw the table with the users, but I would like to add a onclick function to each one of the rows so whenever I click on the row I get the books attached to that user(which are gotten from the database), anyways my question is how can I add a function to each tr each time a tr is generated so when I click on a tr I call a function. I tried to add an eventlistener on the drawUsersTable function to each tr but it does not seem to work.

Here is the code:


  <body>
    <script>
      async function getToken() {
        const response = await fetch("http://localhost:3000/auth", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            user: "jesus",
            password: "1234"
          })
        });
        const { token } = await response.json(); //esta linea no se ejecutara hasta que response este resuelta
        localStorage.setItem("token", token);
      }

      async function printUsers() {
        const token = localStorage.getItem("token");
        const response = await fetch("http://localhost:3000/users", {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        });
        const users = await response.json();
        drawUsersTable(users);
      }

      const drawUsersTable = users => {
        cont = 1;
        const table = document.getElementById("table");
        users.forEach(({ user_id, username, isAdmin }) => {
          
          const firstTD = document.createElement("td");          
          const secondTD = document.createElement("td");
          const thirdTD = document.createElement("td");

          firstTD.innerText = user_id;
          secondTD.innerText = username;
          thirdTD.innerText = isAdmin;

          const tr = document.createElement("tr");
          tr.setAttribute("id", "user_id" + cont);
          tr.addEventListener("click", printBooks(user_id));
          cont = cont + 1;
          tr.append(firstTD, secondTD, thirdTD);
          table.append(tr);
        });
      };
      getToken().then(() => printUsers());

      async function printBooks(userId) {    
        const token = localStorage.getItem("token");        
        const response = await fetch("http://localhost:3000/bookUser/:userId/books", {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        });
        const books = await response.json();
        console.log(books);
      }


    </script>

    <table id="table">
      <tr>
        <td class="id">ID</td>
        <td>Username</td>
      </tr>
    </table>

I tried this but it is not working, instead of adding the onclick method to each row, it prints out all the code on the screen.... any hints?

const drawUsersTable = users => {
        cont = 1;
        const table = document.getElementById("table");
        users.forEach(({ user_id, username, isAdmin }) => {
          const firstTD = document.createElement("td");
          const secondTD = document.createElement("td");
          const thirdTD = document.createElement("td");

          firstTD.innerText = user_id;
          secondTD.innerText = username;
          thirdTD.innerText = isAdmin;

          const tr = document.createElement("tr");
          tr.setAttribute("id", "user_id" + cont);
          tr.onclick =  function(user_id){
            const token = localStorage.getItem("token");
            const response =  fetch("http://localhost:3000/bookUser/:userId/books", {
              headers: {
               Authorization: `Bearer ${token}`,
              "Content-Type": "application/json"
              }
            });
            const books =  response.json();
            console.log(books);
          }
2
  • This might have been already answered here: stackoverflow.com/questions/6658752/… Commented Dec 6, 2019 at 13:31
  • Thanks, I have checked it already but that is Jquery I would like JS solution if possible Commented Dec 6, 2019 at 13:32

2 Answers 2

1

Where you have

const tr = document.createElement("tr");

Can you not add:

tr.onclick = function() { alert('magic'); };
Sign up to request clarification or add additional context in comments.

1 Comment

tr.onclick = printBooks(user_id)
0

element.onclick = functionName() should work.

Check the code here

https://jsfiddle.net/Arpit09/dbxzuyre/17/

4 Comments

Thanks but I already tried adding elemnt.onclick and it did not add any function to the tr... dont know what I am missing...
@jesusfernandez please check the jsfiddler link with the answer
that seems like something I can use I will try later and let you know if it works for my code, thanks a lot!!!!!
still not working I dunno why it does not add any function to my tr...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.