SO-42556213

by David Thomas

HTML

<form action="#">
  <fieldset>
    <legend>Add new details:</legend>
    <label>FirstName
      <input type="text" id="firstN" />
    </label>
    <label>LastName
      <input type="text" id="lastN" />
    </label>
    <label>Points
      <input type="text" id="pnt" />
    </label>
    <button type="button" id="addRow">Add</button>
  </fieldset>
</form>
<table id="myTable">
  <thead>
    <tr>
      <th>Rownumber</th>
      <th>FirstName</th>
      <th>LastName</th>
      <th>Points</th>
    </tr>
  </thead>
  <tfoot>
    <tr class="template">
      <td></td>
      <td data-from="firstN"></td>
      <td data-from="lastN"></td>
      <td data-from="pnt"></td>
    </tr>
  </tfoot>
  <tbody>
  </tbody>
</table>

CSS

body {
  box-sizing: border-box;
}

label {
  display: block;
  width: 55%;
  overflow: hidden;
  margin: 0 0 0.5em 0;
}

table {
  table-layout: fixed;
  width: 90%;
  margin: 1em auto;
  border-collapse: collapse;
}

label input {
  width: 50%;
  float: right;
}

th,
td {
  border-left: 1px solid #000;
  border-bottom: 1px solid #000;
  line-height: 2em;
  height: 2em;
}

th {
  text-align: center;
}

th::after {
  content: ': ';
}

td:first-child,
th:first-child {
  border-left-color: transparent;
}

tbody {
  counter-reset: rownumber;
}

tbody tr {
  counter-increment: rownumber;
}

tbody td:first-child::before {
  content: counter(rownumber, decimal);
}

tfoot tr.template {
  display: none;
}

JavaScript

function addRow() {
  let details = {},
    target = document.querySelector('#myTable tbody'),
    source = document.querySelector('#myTable tfoot tr.template')
    .cloneNode(true),
    inputs = Array.from(
      document.querySelectorAll('form label input')
    );

  inputs.forEach(
    input => details[input.id] = input.value
  );

  Array.from(source.children).forEach(
    cell => cell.textContent = details[cell.dataset.from] || ''
  );

  target.appendChild(source);
  inputs.forEach(
    input => input.value = input.defaultValue
  );
}

document.querySelector('#addRow').addEventListener('click', addRow);