Morteza
Morteza

Reputation: 2153

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 work nice but my del button not work. When del row clicked nothing happened.

Upvotes: 5

Views: 2159

Answers (5)

thecodeparadox
thecodeparadox

Reputation: 87073

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

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191729

this is not going to be span, so it's not going to find the parent. I wouldn't create global functions for these at all nor would I 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>

Upvotes: 1

j08691
j08691

Reputation: 207891

Change your del function to:

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

and your add function to:

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

jsFiddle example.

Upvotes: 1

gdoron
gdoron

Reputation: 150253

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

Upvotes: 1

sushil
sushil

Reputation: 2671

You should use:

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

Upvotes: 0

Related Questions