Javascript Button identify

I have a function that generates a DOM table. Within the table I have multiple buttons. If I generate multiple tables how can I know in wich table got pressed one of the buttons. For this example is the Up button

const row3 = document.createElement("tr");
cell.appendChild(row3);

const buttonUp = document.createElement("button");
row3.appendChild(buttonUp);

buttonUp.addEventListener("click", function() {
  temperatureRoom[numberRoom - 1] = temperatureRoom[numberRoom - 1] + 0.5;
  row2.innerText = `New temperature: ${temperatureRoom[numberRoom-1]}`;
}, true);
buttonUp.addEventListener("click", InsertData, true);

HTML:

<!DOCTYPE html>
<html>

<head>
  <title>Home</title>
</head>

<body>
  <button id="insert">Add a room</button>
  <script type="module">
    import { generateBox } from "http://localhost:8000/home.js";
    var insertBtn = document.getElementById("insert");        insertBtn.addEventListener("click", generateBox, true);
  </script>
</body>

</html>

For example I generate with the function three tables, how do I know in wich table the Up button got pressed?

>Solution :

One way to know which table the button was pressed in is to add a unique identifier to each table and attach it to the button as a data attribute. Then, in the event listener function, you can retrieve the identifier and use it to determine which table was clicked.

Here’s an example:

// Generate table
const table = document.createElement("table");
table.setAttribute("data-table-id", "1"); // Add unique identifier to table

// Generate row and button
const row3 = document.createElement("tr");
const cell = document.createElement("td");
const buttonUp = document.createElement("button");
buttonUp.setAttribute("data-table-id", "1"); // Add unique identifier to button
row3.appendChild(cell);
cell.appendChild(buttonUp);

// Add event listener to button
buttonUp.addEventListener("click", function(event) {
  const tableId = event.target.getAttribute("data-table-id"); // Retrieve table identifier from button
  temperatureRoom[numberRoom - 1] = temperatureRoom[numberRoom - 1] + 0.5;
  row2.innerText = `New temperature: ${temperatureRoom[numberRoom-1]}`;
  InsertData(tableId); // Pass table identifier to function
}, true);

In this example, we’ve added a data-table-id attribute to both the table and the button, with a value of 1. When the button is clicked, we retrieve the data-table-id attribute from the button and pass it to the InsertData function as a parameter, which can then be used to determine which table was clicked.

Leave a Reply