Homunculus Reticulli
Homunculus Reticulli

Reputation: 68446

Removing a row from a when an element in the row is clicked

I have a list of items, which I will be presenting to the user as table rows.

Each row will have a small 'x' image in the top right hand corner, which when clicked will cause the following behaviour:

The html looks something like this:

<html>
    <head>
        <script type="text/javascript" src = jquery.js"></script>
    </head>
    <body>
       <table><tbody>
          <tr>
             <td><div class="delbtn"></div>
                 <div class="rowitem">This one line item</div>
          </tr>
          <tr>
             <td><div class="delbtn"></div>
                 <div class="rowitem">This another line item</div>
          </tr>
          <tr>
             <td><div class="delbtn"></div>
                 <div class="rowitem">blah, blah, blah</div>
          </tr>
          </tbody>
       </table>
       <script type="text/javascript">
           $().ready(function(){
               // What to do ?
            });
       </script>
    </body>
</html>

Clearly, I have to bind to the div.delbtn pattern, but how do I know the row that was clicked on, and how do I delete that row from the table?

Upvotes: 0

Views: 78

Answers (3)

skiss
skiss

Reputation: 213

If you have many rows or intend to add / delete rows after the page has loaded you should use a delegate. Instead of binding a listener to each row it will only bind one listener to the table. Set an id on that table tag (e.g. myTable) and do:

$(document).ready(function() {
   $('#myTable').delegate('tr .delbtn', 'click', function () {
      $(this).parent('td').parent('tr').remove();
   });
});

Also, don't forget to close those td tags.

Upvotes: 0

ipr101
ipr101

Reputation: 24236

Try -

$(document).ready(function() {
    $(".delbtn").click(function() {
        $(this).closest('tr').remove();
    })
});

Demo - http://jsfiddle.net/39pxL/

Upvotes: 1

Marc B
Marc B

Reputation: 360732

$().ready(function() {
   $('.delbtn').click(function() {
       $(this).parent('tr').remove();
   });
});

No need to "know" which row was clicked on, as each DOM node is aware of who its parent node is, and can eaisly move back up the DOM tree using .parent(), to look for a particular ancestor. In this case, you want to nuke a row, so look for an ancestor <tr> of which ever node the click occured in.

Upvotes: 1

Related Questions