Question

I have a dynamically generated table with a button on each row. The button looks like this: (don't worry about the strange id (if this isn't the cause of the error, at least). This is a JavaServer Page (JSP), and the ID of the button contains something useful which I can use later.

<table id="myTableRooms" class="table table-bordered table-hover">
    <thead>
        ... A couple of rows
        <tr><th>buttons</th></tr>
    </thead>
    <tbody>
        ... A couple of rows
        <td>
            <button type="button" class="btn btn-danger btn-sm deleteRoomBtn" id="${room.id} ${i.index}">
            <span class="glyphicon glyphicon-remove-circle"></span>button</button>
        </td>
    </tbody>
</table>

The javascript for this table is as follows:

$(document).ready(function () {
   var table = $('#myTableRooms').DataTable();
   $(table).on( 'click', 'input', function () {
        table.fnDeleteRow( this );
      });
});

When I change the selector from input to tr like in the example it does remove the row of the table when I click on a row. What I want is the row to disappear when I click on the button in the row, so I assume I need to get the correct selector. I tried many things, including .deleteRoomBtn and input, but alas.

Is it just a case of getting the selector right, or is my entire setup wrong?

Was it helpful?

Solution 2

fnDeleteRow() wants a <tr> element as parameter. When clicking the button in your current code, this will be referring to the clicked input element. So what you need to do is find the <tr> element of the button and send that in:

$(document).ready(function () {
   var table = $('#myTableRooms').DataTable();
   $(table).on( 'click', 'input', function () {
        var row = $(this).closest("tr");
        table.fnDeleteRow(row);
      });
});

OTHER TIPS

Something like this probably? http://jsfiddle.net/MnT5y/

Basically, when you click the button, you tell jQuery to find the closest row the clicked button, and simply remove it. Its a simple code, and its a good start for you.

$('button').on('click', function(){
    $(this).closest('tr').fadeOut('slow', function(){
        $(this).remove();
    });
});

Try to change the selector to button instead of input and pass in the row...

$(document).ready(function () {
   var table = $('#myTableRooms').DataTable();
   $(table).on( 'click', 'button', function () {
        var tr = $(this).closest('tr');
        table.fnDeleteRow( tr[0] );
      });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top