Friday, April 29, 2011

Manipulating <td>'s within different <tr>'s

Hello, I'm wondering if the following can be done.

I have a list of 'expenses' that I'm displaying in a table. 4 columns - amount, date, where, and what.

I was thinking I'd like to make each clickable via jQuery which would expand that particular expense, inline, to show a more detailed description.

What I'm trying to do is, on click, replace the contents of the 'tr' with a single 'td' that would contain the extended info. Problem is that 'td' only expands to about a quarter of the table. Is there any way of making it extend to the whole row, while maintaining the widths of the other 'td's in the other rows?

From stackoverflow
  • <td colspan="4"> ?
    
  • Here's what I would do. Working Demo.

    <table id="expenses">
    <thead>
      <tr>
        <td>Amount</td>
        <td>Date</td>
        <td>Where</td>
        <td>What</td>
      </tr>
    </thead>
    <tbody>
      <tr class='expense' id='expense-1'>
        <td>$5.99</td>
        <td>4/2/2009</td>
        <td>Taco Bell</td>
        <td>Chalupa</td>
      </tr>
      <tr class='details' id='details-1'>
        <td colspan='4'>
        It was yummy and delicious
        </td>
      </tr>
      <tr class='expense' id='expense-2'>
        <td>$4.99</td>
        <td>4/3/2009</td>
        <td>Burger King</td>
        <td>Whopper</td>
      </tr>
      <tr class='details' id='details-2'>
        <td colspan='4'>
        The king of burgers, indeed!
        </td>
      </tr>
      <tr class='expense' id='expense-3'>
        <td>$25.99</td>
        <td>4/6/2009</td>
        <td>Olive Garden</td>
        <td>Chicken Alfredo</td>
      </tr>
      <tr class='details' id='details-3'>
        <td colspan='4'>
        I love me some italian food!
        </td>
      </tr>
    </tbody>
    </table>
    

    With styles like these:

    #expenses tr.expense {
        cursor: pointer;
    }
    #expenses tr.details {
        display: none;
    }
    

    And then have Javascript that looks like this:

    $(function() {
        $('tr.expense', '#expenses').click(function() {
            var id = $(this).attr('id').split('-').pop();
            var details = $('#details-'+id);
            if(details.is(':visible')) {
                details.hide();
            } else {
                details.show();
            }
        });
    });
    

    That should do it.

  • Whoops! Looks like I wasn't logged in... now I lost the ability to edit my question.

    Thanks to both of you. Paolo, that code is exactly what I was looking for. Thank you!

    Paolo Bergantino : You're welcome. :)

0 comments:

Post a Comment