简体   繁体   中英

How to delete a table row on button click of corresponding row?

This is my code:

    function deleteHostTable(src) {
        var table = src.parentNode.parentNode.parentNode;
        if(table.rows.length > 1) {             
            table.deleteRow(src.parentNode.parentNode);
        }
         }
    function addHost(src) {
         var table = src.parentNode.parentNode.parentNode;
        var newRow = table.insertRow(table.rows.length-1);

        var cell = newRow.insertCell(newRow.cells.length);

        cell.innerHTML = '<input type="hidden" name = "vtierIdH" value = "vtierId" />'

        cell = newRow.insertCell(newRow.cells.length);
        cell.innerHTML = '<img src="images/minus.gif" onclick="deleteHostTable(this);return false;"/>';

        cell = newRow.insertCell(newRow.cells.length);
        cell.className = "pagetitle";
        cell.innerHTML = '<input type = "text" value="hstst" />';
    }
</script>
<html>
<table id="host#1" index="1">
        <tr>
            <td colspan="10">
            <h2 align="left" class="pagetitle">Sub Account Hosts:</h2>
            </td>
        </tr>
        <tr>
            <input type="hidden" name="vtierIdH" value="<%=vtierId %>" />

            <td><button id="minus" onclick="deleteHostTable(this);"/></td>
            <td class="pagetitle"><input type="text" value="hstst" /></td>
        </tr>
        <tr>
            <td><button  onclick="addHost(this);"></td>
        </tr>
    </table>
</html>

Now, when i click the button corresponding to a button, this code deletes the uppermost row and not the row corresponding to that button which is clicked. How can i delete the row corresponding to the button in that row?

Just change your remove function to

function deleteHostTable(src) {
    var row = src.parentNode.parentNode;
    row.parentNode.removeChild(row);
}

The reason it's not working with deleteRow is that it expects the index of the row to be passed while you are passing an object.

You must pass "index" to the table.deleteRow function, not the element.

function deleteHostTable(src) {

    var table = src.parentNode.parentNode.parentNode;
    var row = src.parentNode.parentNode;
    for(var i = table.rows.length; i--; )
    {
        if ( table.rows[i] == row )
        {
            table.deleteRow(i);
            return;
        }
    }

}

this function should work.

You also can use src.parentNode.parentNode.parentNode.removeChild(src.parentNode.parentNode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM