I have a document with many buttons, all of which contain onclick="myFunction()"
inside the button tag. When I click the 1st button, 1 row is added to my table, as desired. However, as I click the 2nd button, 2 rows are added to my table, and so on, i.e. rows are added on the ith button click. How can I fix my JavaScript function to only add 1 row for each new button click?
function myFunction() {
table_body = document.getElementById("t_body");
document.addEventListener("click", (e) => {
let element = e.target;
if (element.tagName == "BUTTON") {
row = table_body.insertRow();
cell1 = row.insertCell();
cell1.innerHTML = element;
cell2 = row.insertCell();
cell2.innerHTML = element.id;
cell3 = row.insertCell();
cell3.innerHTML = element.id;
cell4 = row.insertCell();
cell4.innerHTML = element.id;
element.style.backgroundColor = "#004d00";
element.style.color = "white";
}
});
}
CodePudding user response:
I would share more code to see what's happening. Initially looks like you can be adding multiple event listeners to BUTTON.
try target the button by a class. and make sure myFunction is only called once.
<html>
<body>
<table id="table">
<tr>
<td><BUTTON class='form-button' id='example' >TEST</BUTTON></td>
<td>example</td>
</tr>
</table>
<br>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
myFunction();
});
function myFunction() {
table_body = document.getElementById("table");
document.addEventListener('click', (e) => {
console.log('clicked');
let element = e.target;
if(element.classList.contains('form-button')) {
row = table_body.insertRow()
cell1 = row.insertCell();
cell1.innerHTML = 'Hello';
cell2 = row.insertCell();
cell2.innerHTML = element.id;
element.style.backgroundColor = '#004d00';
element.style.color = 'white';
}
});
}
</script>
</body>
</html>