ricster ricster - 1 month ago 5
Javascript Question

Can't add data to table with plain JS

I'm learning Javascript and I'm trying to implement a small "ID and Task" table, but somehow it only works when I enter only 1 type of data such as only ID or only task, when I enter 2 data at the same time, nothing happens. I'd be grateful if you tell me what is the problem and how can I fix it. Thank you.

Here's my HTML

<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>

New task:<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>

<h3>Task Table</h3>
<div id = "excell">
<table id = "table" cellspacing = "0px" cellpadding = "25px" text-align = "center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>

<tbody>

</tbody>
</table>
</div>
</body>


and here's my JS

function addData() {

var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");

tr.innerHTML = rows;
tbody.appendChild(tr)
}

Answer

Actual problem with your code is, you have used Submit button. Normally when a submit button is hit it post the data to action property of the form tag, which means transfer the page to next; if action property is not given, it give flickering effect and stay with current page and made all components with empty. The same is happen in your code also. Better Change the code input type="Submit" value="Add" onClick="addData();" into input type="BUTTON" value="Add" onClick="addData();"

and try its worked fine.