Reputation: 255
Heyy, I am new to javascript, and i am trying to understand how delete and update buttons work. i saw many suggestions but my delete button doesnt seem to work, I dont know where i went wrong. Help please
<script type="text/javascript">
function Delete(object){
table = document.getElementById("table");
row = document.getElementById(object);
table.removeChild(row);
};
</script>
<table id="table" class="table .table-bordered" style="width:50%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sara</td>
<td>1-12-1990</td>
<td>Female</td>
<td>Married</td>
<button>Edit</button>
<button onclick="Delete">Delete</button>
</tr>
</tbody>
</table>
and one more problem is that the delete button is showing on top of the table not in the action column why?
Upvotes: 1
Views: 229
Reputation: 782489
You need to pass the element as an argument to Delete()
. The element is not an ID, so you shouldn't use getElementById
with it, just access the element directly. You can use parentElement
to go up the DOM hierarchy to find the containing row and table.
To solve the layout problem, you need to put the buttons inside <td>
. Everything in a table row has to be in either <td>
or <th>
.
function Delete(object) {
var row = object.parentElement.parentElement;
var table = row.parentElement;
table.removeChild(row);
};
<table id="table" class="table .table-bordered" style="width:50%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sara</td>
<td>1-12-1990</td>
<td>Female</td>
<td>Married</td>
<td><button>Edit</button></td>
<td><button onclick="Delete(this)">Delete</button></td>
</tr>
</tbody>
</table>
Upvotes: 3
Reputation: 1161
The buttons should also go into a table cell
<td>
<button>Edit</button>
<button onclick="Delete();">Delete</button>
</td>
You also have to change the click event to be as above:
<button onclick="Delete();">Delete</button>
Upvotes: 0