Retain DOM values when removing rows from table with javascript

32 Views Asked by At

The issue I'm having is when I try to update the remaining rows in a table .outerHTML so that the name attributes are sequential. It's necessary as the .net backend expects the array to start at zero and be sequential.

If you have more than one row with entries, then delete a row, when updating the outerHTML the DOM values are removed and everything resets to blank. Is there a way to retain the values entered? It works fine not updating the outerHTML but that won't work for the backend.

https://jsfiddle.net/y2dxus1m/

    function addBenefit() {
      //gets the table and adds a new row based on length
      var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
      var myHtmlContent = '<td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].FirstName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].LastName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Amount"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Source"></td><td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>';
      var newRow = tableRef.insertRow(tableRef.rows.length);
      newRow.innerHTML = myHtmlContent;
    }

    function removeRow(a) {
      var row = a.parentNode.parentNode;
      row.parentNode.removeChild(row);
      var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
      for (var i = 0; i < tableRef.rows.length; i++) {
        console.log(tableRef.rows[i].outerHTML)
        
        //Issue is here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        tableRef.rows[i].outerHTML = tableRef.rows[i].outerHTML.replace(/(\[).+?(\])/g, "[" + i + "]");
        console.log(tableRef.rows[i].outerHTML)
      }
    }
<table class="deptTable" id="benefitsField">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Weekly Benefit Amount</th>
      <th>Source</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].FirstName" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].LastName" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].Amount" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].Source" /></td>
      <td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>
    </tr>
  </tbody>
</table>
<button onclick="addBenefit()">Add</button>

1

There are 1 best solutions below

0
Thomas Cowdrey On BEST ANSWER

Adding the following function to reset the table rows after a row was removed resolved the issue. Fiddle updated

function setIndex() { $("td.index").each(function (index) { $(this).text(++index); }); }