I am having issues with inserting rows using a button in Javascript. When I click the button, rows are being inserted unexpectedly as shown in the images below. Additionally, I also need a delete row button to work in a similar manner. Thank you for any help.
Click here to view table image
Here is my code:
<style>
table {
border-collapse: collapse;
margin: 100px;
}
table, td, th {
border: 1px solid black;
padding: 10px;
}
</style>
<table id="t1">
<tr>
<th>Task No</th>
<th>Done/In Progress</th>
<th>Deadline</th>
<th>Task</th>
</tr>
<tr>
<td>1.</td>
<td>
<input type="checkbox" />
</td>
<td></td>
<td>
<input type="text" style="width:100%;" />
</td>
</tr>
</table>
<input style="margin-top:-200px; padding:10px" type="button" value="Add Row" onclick="add()" />
Javascript:
<script>
function add() {
var num = document.getElementById("t1").rows.length;
console.log(num);
var x = document.createElement("tr");
var a = document.createElement("td");
var anode = document.createTextNode(num);
a.appendChild(anode);
x.appendChild(a);
a = document.createElement("td");
anode = document.createElement("input");
var b = document.createAttribute("type");
b.value = "checkbox";
anode.setAttributeNode(b);
a.appendChild(anode);
x.appendChild(a);
a = document.createElement("td");
anode = document.createElement("input");
b = document.createAttribute("type");
b.value = "text";
anode.setAttributeNode(b);
a.appendChild(anode);
x.appendChild(a);
document.getElementById("t1").appendChild(x);
}
</script>