0

Suppose you have a html table of the

<form id="myForm">
<table id="myTable">
    <tr>
        <th>One</th>
        <th>Two</th>
        <th>Three</th>

    </tr>

    <tr>
        <td>Alpha</td>
        <td>Bravo</td>
        <td><a href="javascript:remove(1)">X</a></td>
    </tr>

    <tr>
        <td>Charlie</td>
        <td>Delta</td>
        <td><a href="javascript:remove(2)">X</a></td>
    </tr>

    <tr>
        <td>Echo</td>
        <td>Foxtrot</td>
        <td><a href="javascript:remove(3)">X</a></td>
    </tr>
</table>
</form>
<a href="javascript:reset()">Reset</a>

I have the following javascript

var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;

function remove(rowID)
{
    table.deleteRow(rowID);
}

function reset()
{
    form.innerHTML = formSave;
}

For some reason, the remove() function works fine, but after using the reset() function, it no longer works. Can anyone tell me why this is?

M Smith
  • 410
  • 6
  • 16
  • Does the function even get called? – toddmo Jun 18 '17 at 23:52
  • Has to do with event delegation: [link1](https://davidwalsh.name/event-delegate), [link2](https://learn.jquery.com/events/event-delegation/), [link3](https://stackoverflow.com/a/1688293/3407923) (the jQuery link might still be useful for understanding the principle). Or just google "js event delegation" and see which site explains it best for you. – myfunkyside Jun 18 '17 at 23:53
  • Change `table.deleteRow(rowID);` to `document.getElementById('myTable').deleteRow(rowID);` and it probably will work after calling reset – myfunkyside Jun 18 '17 at 23:58
  • Strictly speaking, I'm actually not sure if I should call this EVENT delegation, but the same principle applies because when you remove the table and add it again, the `var table` doesn't reference the new table. – myfunkyside Jun 19 '17 at 00:04

1 Answers1

0

As var table is a live 'Element object' it's properties are updated each time you delete a row. By the time you deploy the reset() function var table references less Children than the restored HTML. Opening the console will show you have an indexing error on subsequent uses of the function bound to "X".

You can remedy this by re-acquiring the element in the reset function, like so...

var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;

function remove(rowID) {
    table.deleteRow(rowID);
}

function reset() {
    form.innerHTML = formSave;
    /* re-acquire 'new' (inserted) table */
    table = document.getElementById('myTable');
}

Hope that helped :)

Brian Peacock
  • 1,571
  • 12
  • 22