This is my js code:
<script>
function add(){
$('#myTable tr:last').after('<tr><td>4<span onclick="del()">del row</span></td></tr>');
}
function del(){
$(this).parent('tr').remove();
}
</script>
and html:
<table id="myTable" border="1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
<span onclick="add()">add row</span>
My add button work nice but my del button not work. When del row clicked nothing happened.
function add(){
$('#myTable tr:last').after('<tr><td>4<span onclick="del(this)">del row</span></td></tr>');
}
function del(el) {
$(el).closest('tr').remove()
}
Working sample
I think more easy will be that, if you add a class to the del row span
and remove onclick
like following:
function add(){
$('#myTable tr:last').after('<tr><td>4<span class="delRow">del row</span></td></tr>');
}
and set delegate event handler like following:
$('#myTable').on('click', 'span.delRow', del);
and write your del()
function like following:
function del() {
$(this).closest('tr').remove();
}
Working Sample
Don't forget to place your whole code within
$(document).ready(function() {..})
in short
$(function() {..})
Couple of things.
1. this
when using inline script is the window.
2. you need to replace parent
with closest
.
3. better use delegate event
function del(){
$(this).closest('tr').remove(); // closest!!
}
$('#myTable').on('click', 'span', del);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With