Nevi Nevi - 3 months ago 9
HTML Question

Adding Data to Table Dynamically

I'm trying to add data to html table dynamically i'm almost half way getting the right code but it concatenates the two data in textboxes then add it to the first code, what could be the problem?

Here is the js fiddle



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);
}

#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>




Answer

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

function AddDataToTable() {
  var id = document.getElementById("id1").value;
  var firstname = document.getElementById("firstname").value;
  var trNode = document.createElement("tr");
  var tdNode1 = document.createElement("td");
  var tdNode2 = document.createElement("td");
  trNode.appendChild(tdNode1);
  trNode.appendChild(tdNode2);
  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