Nevi Nevi - 4 months ago 9
HTML Question

Adding data to a table dynamically

I'm trying to add rows to a table dynamically but it concatenates the data of both textboxes then add it to the first

<td>
, what could be the problem?



function AddDataToTable() {
var id = document.getElementById("id1").value;
var firstname = document.getElementById("firstname").value;
var trNode = document.createElement("tr");
var tdNode = document.createElement("td");
trNode.appendChild(tdNode);
var trID = document.createTextNode(id);
var trFirstName = document.createTextNode(firstname);
tdNode.appendChild(trID);
tdNode.appendChild(trFirstName);
document.getElementById("productable").appendChild(trNode);
}

<table id="productable" border="1">
<tr>
<th>ID</th>
<th>Item</th>
</tr>
<tr>
<td>1</td>
<td>Shoes</td>
</tr>
</table>
<br/>
<input type="text" name="id" id="id1">
<input type="text" name="firstname" id="firstname">
<input type="button" onclick="AddDataToTable()" value="Add" />




Answer

Need to create two td elements and append the text node twice respective to them.

function AddDataToTable() {
  var productable = document.getElementById("productable");
  var id = document.getElementById("id1").value;
  var firstname = document.getElementById("firstname").value;
  var trNode = document.createElement("tr");
  // creating a delete button.
  var btn = document.createElement("BUTTON");
  btn.innerHTML = 'delete';
  btn.addEventListener("click", function () {
    
    productable.removeChild(trNode);
  });
  
  var tdNode1 = document.createElement("td");
  var tdNode2 = document.createElement("td");
  trNode.appendChild(tdNode1);
  trNode.appendChild(tdNode2);
  trNode.appendChild(btn);
  var trID = document.createTextNode(id);
  var trFirstName = document.createTextNode(firstname);
  tdNode1.appendChild(trID);
  tdNode2.appendChild(trFirstName);
  document.getElementById("productable").appendChild(trNode);
}
#productable,
th,
td {
  border: 1px dotted grey;
}
td {
  padding: 20px;
}
th {
  text-align: center;
}
<title>Table</title>

<body>
  <table id="productable">
    <tr>
      <th>ID</th>
      <th>Item</th>
    </tr>
    <tr>
      <td>1</td>
      <td>Shoes</td>
    </tr>
  </table>
  <br/>
  <input type="text" name="id" id="id1">
  <input type="text" name="firstname" id="firstname">
  <input type="button" onclick="AddDataToTable()" value="Add" />
</body>

Comments