Javascript – Add a blank row in HTML Table

htmljavascript

I have an HTML table that adds a new row below where the button in current row is located. Currently when the row is created it generates a clone of the row above including the data. I would like this to be a row that has no entry for the input values rather than a clone of the values above.

Javascript

function addRow(row)
{
    var i = row.parentNode.parentNode.rowIndex;
    var tr = document.getElementById('Table').insertRow(i+1);
    tr.innerHTML = row.parentNode.parentNode.innerHTML;
    tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
} 
<table id="Table" border="1">
    <tr>
        <td><b>Measured Depth</b></td>
        <td><b>Inclination</b></td>
        <td><b>Azimuth</b></td>
        <td><b>Delete?</b></td>
        <td><b>Add Row?</b></td>
    </tr>
    <tr>
        <td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
        <td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
        <td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
        <td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
        <td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
    </tr>
</table>

Best Answer

after you add a row, you can just set the values of all inputs in that row to "". get all the inputs of type text using tr.querySelectorAll("input[type='text']") and using a loop set values of all to ""

  function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for(var i=0; i<inputs.length; i++)
   inputs[i].value = "";
}
<table id="Table" border="1">
        <tr>
            <td><b>Measured Depth</b></td>
            <td><b>Inclination</b></td>
            <td><b>Azimuth</b></td>
            <td><b>Delete?</b></td>
            <td><b>Add Row?</b></td>
        </tr>
        <tr>
            <td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
            <td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
            <td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
            <td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
            <td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
        </tr>
</table>

Related Topic