del r...">

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.

+5
source share
5 answers

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()
}

Working example


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();
}

Working example


And one important note

Remember to put all the code in

$(document).ready(function() {..})

shorter

$(function() {..})
+4
source

A couple of things.

1. this inline script - .
2. parent closest.
3. delegate event

function del(){
     $(this).closest('tr').remove(); // closest!!
}    

$('#myTable').on('click', 'span', del);
+1

Change the del function:

function del(row){
  $(row).closest('tr').remove();
}​

and your add function:

$('#myTable tr:last').after('<tr><td>4<span onclick="del(this)">del row</span></td></tr>');

JsFiddle example .

+1
source

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>
+1
source

You should use:

$(this).parent('#myTable tr').remove();
0
source

All Articles