1

This my javascript, once I click a button it removes that row but then the other buttons do nothing.

var removeRowBtns = document.getElementsByClassName("removeRowBtn")
var tableRows = document.getElementsByTagName("tr")

for(var i = 0; i < removeRowBtns.length; i++) {
removeRowBtns[i].addEventListener("click", function() {
  tableRows[i].parentNode.removeChild(tableRows[i]);
    });
}

Heres my HTML:

<table class="table table-bordered">
<tr>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Email Address</th>
  <th>Remove</th>
</tr>
<tr>
  <td>name</td>
  <td>name</td>
  <td>email</td>
  <td><button class="btn btn-danger removeRowBtn">X</button></td>
</tr>
<tr>
  <td>name</td>
  <td>name</td>
  <td>email</td>
  <td><button class="btn btn-danger removeRowBtn">X</button></td>
</table>
  <script type="text/javascript" src="table.js"></script>
jmona789
  • 2,711
  • 6
  • 24
  • 57
  • 1
    Look into javascript closures. The value of `i` through the loop doesn't propagate quite the way you think it does.The other alternative is to call the same function for each of the buttons. This function will get a reference to the button that was clicked, via the `this` keyword. From there, you walk back up the DOM tree until you get to the TR element that contains it. You then nuke that TR. – enhzflep Nov 16 '15 at 05:49
  • There must be a thousand questions here on exactly the same topic. – RobG Nov 16 '15 at 06:33

1 Answers1

1

Your event handler executes long after the loop is finished.

Your variable i is always the last value of the loop. Associate the button with the table row you need to delete and use e.target of the event handler to get the reference to it.

For example, you can have this type of markup:

<tr id="r15"></tr>  <input type="button" rawLink="r15" value="Delete"></input>

and JS like this

for(var i = 0; i < removeRowBtns.length; i++) {
   removeRowBtns[i].addEventListener("click", function(e) {
      var raw = document.getElementById(e.target.getAttribute("rawLink"));
      raw.parentNode.removeChild(raw);
    });
}
Charlie
  • 22,886
  • 11
  • 59
  • 90