Onclick event in dynamically created button in javascript

Requirements: I have one table with one row and three columns. there is a button in the first column. when I click on this button, a new row should be added to the table, and when I click on a button in a newly added row (i.e. it is created dynamically), it should add a new row.

only the last line of the button should add a new line, all previous buttons should be changed to remove the buttons.

- java script function.

<html> <head runat="server"><TITLE>Add/Remove dynamic rows in HTML table</TITLE> <SCRIPT language="javascript"> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var element1 = document.createElement("input"); element1.setAttribute('type','button'); element1.setAttribute('name','Add Row1'); element1.setAttribute('value','Add Row'); cell1.appendChild(element1); var cell2 = row.insertCell(1); var element2 = document.createElement("input"); element2.type = "text"; cell2.appendChild(element2); var cell3 = row.insertCell(2); var element3 = document.createElement("input"); element3.type = "checkbox"; cell3.appendChild(element3); element1.onclick=addRow(tableID); } </HEAD> <BODY> <TABLE id="dataTable" width="250px" border="1"> <TR> <td><INPUT type="button" value="Add Row" name="Add Row" onclick="addRow('dataTable')"/></td> <TD><INPUT type="text" /></TD> <TD><INPUT type="checkbox" name="chk"/></TD> </TR> </TABLE> </BODY> </html> 

when I run this code, I get one row with three columns. when I click the button in the first line .. its adding lines is endless. please help me get the result.

early.

+4
source share
2 answers

The reason this code does not work is as follows:

 element1.onclick=addRow(tableID); 

What you expect is to assign the value 'addRow (tableID)' to the onclick attribute of the newly created item.

What you are actually doing is calling the addRow function right away, causing the program to loop indefinitely.

The shortest way to fix this is to use something like this:

 element1.setAttribue('onclick','addRow("'+tableID+'")'); 
+2
source

This is because your function calls itself:

 **function addRow(tableID) {** var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var element1 = document.createElement("input"); element1.setAttribute('type','button'); element1.setAttribute('name','Add Row1'); element1.setAttribute('value','Add Row'); cell1.appendChild(element1); var cell2 = row.insertCell(1); var element2 = document.createElement("input"); element2.type = "text"; cell2.appendChild(element2); var cell3 = row.insertCell(2); var element3 = document.createElement("input"); element3.type = "checkbox"; cell3.appendChild(element3); **element1.onclick=addRow(tableID);** } 
+1
source

Source: https://habr.com/ru/post/1442919/


All Articles