javascript - Can't properly delete rows from a dynamically generated table using a button -


i have following code supposed generate rows in table each row has own content , delete button.

<!doctype html> <html>     <head>         <title>table</title>     </head>     <body>         <input id="inputtext">         <button onclick = "addrow()">add text</button>          <table id = "table">         </table>         <script>             function addrow(){                  var newrow = document.createelement("tr");                 var col1 = document.createelement("td");                 var col2 = document.createelement("td");                 newrow.appendchild(col1);                 newrow.appendchild(col2);                  var button = document.createelement("button");                 button.innerhtml = "delete";                  button.onclick = function () {                     var index = this.parentnode.parentnode.rowindex;                     document.getelementbyid("table").deleterow(index);                 }                 col1.appendchild(button);                   var enteredtext = document.getelementbyid("inputtext").value;                 col2.innerhtml = enteredtext;                  document.getelementbyid("table").appendchild(newrow);              }         </script>     </body> </html> 

the problem no matter delete button press, deletes last row. tried using console.log(this.parentnode.parentnode) see if returns right <tr> object, , indeed does. reason, attribute rowindex -1 no matter button pressed; hence last row deleted. mean each dynamically generated <tr> doesn't know row index?

you can use htmltableelement.insertrow() function instead.

var newrow = document.getelementbyid("table").insertrow(); // newrow.rowindex return proper index 

here working fiddle

update

it bug in webkit layout engine, (that moved forked blink engine well). why works in firefox not in earlier versions of chrome (blink) or safari (webkit).

the bug report here, it's fixed now.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -