add and delete row dynamically
jquery
Solution
Little change with your code
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
Another easier approach, not need radical change in your code
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
And one important note
Don't forget to place your whole code within
$(document).ready(function() {..})
in short
$(function() {..})
Problem
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.