0

I've been scratching my head about why my code is acting the way it is.

My question is that why when I add a table row using my function addRow, it resets all of the input values of previous rows?

Below is a code snippet displaying my issues..

function addRow() {
   //the html for adding a row (contains the row tag and inputs)
   htmlString = '<tr><td><input type="text"></input></td></tr>';
   //add the html string to the tbody of the tableTestSamples
   document.getElementById("testTable").getElementsByTagName("tbody")[0].innerHTML += htmlString;
}
<table id="testTable">
  <tbody>
    <tr>
      <td>
        <input type="text"></input>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>
        <input type="button" onclick="addRow()" value="Add Row"></input>
      </td>
    </tr>
  </tfoot>
</table>

It adds a row.. except its resetting any previously entered values. Why is that?

Thanks!

1
  • 1
    That's because modifying the innerHTML of an element causes it to replace all existing children. Try to use appendChild() instead. Commented Feb 14, 2018 at 18:59

1 Answer 1

3

The problem is that you're mutating the innerHTML of the table. This causes the browser to treat the contents of the table as a string of HTML, reparse the HTML and then replace the contents of the table. Since the browser doesn't update the innerHTML to reflect values entered into an input tag, those values will get lost in this process.

To avoid resetting the input values you need to manipulate the DOM, rather than manipulate the underlying source code. You can still use HTML to create your new row, but you need to add it to the table using a function like: appendChild().

Example:

function addRow() {
  var row = document.createElement('tr');
  row.innerHTML = '<td><input></td>';

  var table = document.getElementById('the-table');
  table.appendChild(row);
}
<table id="the-table">
  <tr>
    <td><input></td>
  </tr>
</table>
<button onclick="addRow()">Add Row</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.