Add and delete row dynamically
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 works fine, but the del button doesn't work. When the del row button was pressed, nothing happened.
A 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()
}
Another simple approach that does not require drastic changes in your code
I think it will be easier if you add the class to del row spanand delete it onclickas follows:
function add(){
$('#myTable tr:last').after('<tr><td>4<span class="delRow">del row</span></td></tr>');
}
and set the delegate event handler as follows:
$('#myTable').on('click', 'span.delRow', del);
and write the function del()as follows:
function del() {
$(this).closest('tr').remove();
}
And one important note
Remember to put all the code in
$(document).ready(function() {..})
shorter
$(function() {..})
thiswill not cover, so he will not find a parent. I would not create global functions for them at all, and would not use script attributes. I would rewrite it as:
<table id="myTable" border="1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
<span id="add">add row</span>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$("#add").on('click', function () {
$('#myTable tr:last').after(
$("<tr>")
.append($("<td>", {text: '4'})
.append($("<span>", {text: 'del row'})
.on('click', function () {
$(this).closest('tr').remove();
})
)
)
);
});
</script>