Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: remove the closest <tr> with a dynamically added button

i am unable to remove a row in table using dynamically generated buttons. The main problem is that the "alert()" does not work. How do i catch the 'click' event?

jQuery:

$("#officers-table").on('click', '.remove-officer-button', function(e) {
    var whichtr = $(this).closest("tr");

    alert('worked'); // Alert does not work
    whichtr.remove();      
});

HTML/PHP (updated the code)

<table id="officers-table" class="ui-widget ui-widget-content">
<?php if($num_officers > 0): ?>
    <thead>
      <tr class="ui-widget-header ">
        <th>Name</th>
        <th>Director</th>
        <th>Shareholder</th>
        <th>Secretary</th>
        <th colspan="2">Options</th>
      </tr>
    </thead>
<?php endif; ?>
<tbody>
<?php foreach ($officers as $item): ?>
  <tr>
    <td><?=$item->name?> <?=$item->lastname?></td>
    <td><?=$item->is_director?></td>
    <td><?=$item->is_shareholder?></td>
    <td><?=$item->is_secretary?></td>
    <td>Edit</td>
    <td><button type="button" value="<?=$item->id?>" class="remove-officer-button">Remove</button></td>
  </tr>     
<?php endforeach; ?>
  </tbody>
</table>
like image 426
chuckfinley Avatar asked Jan 25 '13 11:01

chuckfinley


1 Answers

Try this (Works in JSFiddle):

$(".remove-officer-button").on('click', function(e) {
    var whichtr = $(this).closest("tr");
    alert('worked'); // Alert does not work
    whichtr.remove();      
});

Edit
As everyone said, your code seems to work fine as is. Check this JSFiddle:
Original Code: http://jsfiddle.net/mkqU2/1/

You can use the above code as an alternative, but it sounds like you have some other javascript error causing the script to break.

Also.. Make sure you code is inside the DOM Ready event. If its not, Nothing happens when you click the button.
The below jsfiddle replicates your error, the click event don't fire if not wrapped within the DOM Ready event, or window load event.
Not Inside DOM Ready: http://jsfiddle.net/mkqU2/2/

like image 125
Anil Avatar answered Sep 23 '22 21:09

Anil