I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click “add” button, a new row gets added to the table, but when I click the “delete” button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
JavaScript
x
5
1
function deleteRow(row){
2
var d = row.parentNode.parentNode.rowIndex;
3
document.getElementById('dsTable').deleteRow(d);
4
}
5
HTML code
JavaScript
1
22
22
1
<table id = 'dsTable' >
2
<tr>
3
<td> Relationship Type </td>
4
<td> Date of Birth </td>
5
<td> Gender </td>
6
</tr>
7
<tr>
8
<td> Spouse </td>
9
<td> 1980-22-03 </td>
10
<td> female </td>
11
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
12
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
13
</tr>
14
<tr>
15
<td> Child </td>
16
<td> 2008-23-06 </td>
17
<td> female </td>
18
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
19
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
20
</tr>
21
</table>
22
Advertisement
Answer
JavaScript with a few modifications:
JavaScript
1
5
1
function deleteRow(btn) {
2
var row = btn.parentNode.parentNode;
3
row.parentNode.removeChild(row);
4
}
5
And the HTML with a little difference:
JavaScript
1
24
24
1
<table id="dsTable">
2
<tbody>
3
<tr>
4
<td>Relationship Type</td>
5
<td>Date of Birth</td>
6
<td>Gender</td>
7
</tr>
8
<tr>
9
<td>Spouse</td>
10
<td>1980-22-03</td>
11
<td>female</td>
12
<td><input type="button" value="Add" onclick="add()"/></td>
13
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
14
</tr>
15
<tr>
16
<td>Child</td>
17
<td>2008-23-06</td>
18
<td>female</td>
19
<td><input type="button" value="Add" onclick="add()"/></td>
20
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
21
</tr>
22
</tbody>
23
</table>•••••••••••••••••••••••••••••••••••
24