Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add and delete row dynamically

Tags:

jquery

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.

like image 796
Morteza Avatar asked Jun 13 '12 16:06

Morteza


2 Answers

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() {..})
like image 157
thecodeparadox Avatar answered Oct 14 '22 15:10

thecodeparadox


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);
like image 41
gdoron is supporting Monica Avatar answered Oct 14 '22 15:10

gdoron is supporting Monica