views:

67

answers:

2

I'm looking for a simple, effective technique for adding or deleting a row in a html table using JavaScript. (Without using jQuery)

A: 

I wrote this a month ago..Its not the best way

<html>
<head>
        <title>
                Crap work
        </title>
<script type="text/javascript">

function add_row()
{
        var table = document.getElementById('table');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "text";
        cell1.appendChild(element1);     
          var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.type = "text";
        cell2.appendChild(element2);
        var cell3 = row.insertCell(2);
        cell3.innerHTML = ' <span onClick="edit(this)">Edit</span>/<span onClick="delete_row(this)">Delete</span>';
        cell3.setAttribute("style", "display:none;");
        var cell4 = row.insertCell(3);
        cell4.innerHTML = '<span onClick="save(this)">Save</span>';
}


function save(e)
{
    var elTableCells = e.parentNode.parentNode.getElementsByTagName("td");
    elTableCells[0].innerHTML=elTableCells[0].firstChild.value;
    elTableCells[1].innerHTML=elTableCells[1].firstChild.value;
    elTableCells[2].setAttribute("style", "display:block;");
    elTableCells[3].setAttribute("style", "display:none;");
}
function edit(e)
{
    var elTableCells = e.parentNode.parentNode.getElementsByTagName("td");
    elTableCells[0].innerHTML='<input type="text" value="'+elTableCells[0].innerHTML+'">';
    elTableCells[1].innerHTML='<input type="text" value="'+elTableCells[1].innerHTML+'">';
    elTableCells[2].setAttribute("style", "display:none;");
    elTableCells[3].setAttribute("style", "display:block;");
}

function delete_row(e)
{
    e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
}
</script>
</head>
<body >
    <div id="display">
    <table id='table'>
        <tr id='id'>
            <td>
                Piemesons
            </td>

            <td>
                    23
            </td>   
            <td >
                <span onClick="edit(this)">Edit</span>/<span onClick="delete_row(this)">Delete</span>
            </td>   
            <td style="display:none;">
                <span onClick="save(this)">Save</span>
            </td>   
        </tr>   
    </table>    
        <input type="button" value="Add new row" onClick="add_row();" />
    </div>
</body> 
piemesons
+4  A: 
var theTable = document.getElementById("theTable");
theTable.deleteRow(0);  //0 being first row.
Babiker
YES. It's that simple. While the DOM is far from perfect, it usually isn't that hard.
Tim Down