Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a row from a table

I am creating a responsive data table that adds a row each time I click on a add button that is in the end of the row. And the add button turns into a delete button. Here's the code I made

For the Table:

<table id="invoice_table_data">
<tr id="last_row">
        <td contenteditable id="item_name"></td>
        <td contenteditable id="item_code"></td>
        <td contenteditable id="description"></td>
        <td>
            <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>
        </td>
    </tr>
</table>

When for adding is clicked:

$("#btn_add").click(function() {
$("#invoice_table_data").append('<tr id="myTableRow'+'" ><td id="item_name'+n+'">'+item_name+'</td><td id="item_code'+n+'"> '+item_code+'</td><td id="description'+n+'">'+description+'</td><td><button type="button" name="delete_" id="delete_" data-idx="'+n+'">x</button></td></tr>');
n+=1;

And my delete function:

$('#delete_').click( function () {
var nb=$(this).data('idx');
$("#last_row"+nb).remove();
});

However when I click on delete nothing seems to happen. Can anybody help?

like image 358
eBourgess Avatar asked Dec 29 '16 13:12

eBourgess


2 Answers

Identifiers in HTML must be unique, So create the element using CSS class. then Class Selecctor can be used.

Change script to render HTML as

<button type="button" class="delete_">x</button>

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

Use .on() method with Event Delegation approach while generating elements dynamically. So change your code to

$("#invoice_table_data").on('click', ".delete_", function(){
    $(this).closest('tr').remove();
});

var n = 1;
$("#btn_add").click(function() {
  $("#invoice_table_data").append('<tr><td>item_name' + n + '</td><td><button type="button"  class="delete_" data-idx="' + n + '">x</button></td></tr>');
  n += 1;
});

$("#invoice_table_data").on('click', ".delete_", function() {
  $(this).closest('tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="invoice_table_data">
  <tr id="last_row">
    <td id="item_name"></td>
    <td>
      <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>
    </td>
  </tr>
</table>
like image 132
Satpal Avatar answered Oct 01 '22 04:10

Satpal


Use attribute selector and event delegation

$(document).on('click', "[id^='delete_']", function () {
  var nb=$(this).data('idx');
   $("#last_row"+nb).remove();
});
like image 24
Sudharsan S Avatar answered Oct 01 '22 02:10

Sudharsan S