2

Similar questions have been asked but I am not sure if they match this particular scenario,

I have a html table as bellow. What I am trying to achieve is hide/show columns 2 and 3 whenever a there is a click anywhere in column 1.

How can I achieve toggling showing column 2 and 3 with jQuery?

<table id="my_table">
    <thead>
        <tr>
            <th id="col1">First</th>
            <th id="col2">Second</th>
            <th id="col3">Third</th>
            <th id="col4">Fourth</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td id="col1">1</td>
            <td id="col2">1.1</td>
            <td id="col3">1.2</td>
            <td id="col4">1.3</td>
        </tr>
        <tr>
            <td id="col1">2</td>
            <td id="col2">2.1</td>
            <td id="col3">2.2</td>
            <td id="col4">2.3</td>
        </tr>
        <tr>
            <td id="col1">3</td>
            <td id="col2">3.1</td>
            <td id="col3">3.2</td>
            <td id="col4">3.3</td>
        </tr>
        <tr>
            <td id="col1">4</td>
            <td id="col2">4.1</td>
            <td id="col3">4.2</td>
            <td id="col3">4.3</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th id="col1">f1</th>
            <th id="col2">f2</th>
            <th id="col3">f3</th>
            <th id="col4">f4</th>
        </tr>
    </tfoot>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
emt14
  • 4,846
  • 7
  • 37
  • 58

2 Answers2

3
var rows = $('tr');
rows.find('th:first-child, td:first-child').on('click', function() {
    rows.find('td:eq(1), td:eq(2)').toggle()
    rows.find('th:eq(1), th:eq(2)').toggle()

    /* or simply 
       rows.find('td:eq(1), td:eq(2), th:eq(1), th:eq(2)').toggle(); */
});

example jsbin : http://jsbin.com/ucewoz/2/edit

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

You can't use the same IDs in each row. IDs have to be unique. You should use classes instead. Then you could write:

$('.col1').click(function() {
    $('.col2, .col3').toggle();
});
Barmar
  • 741,623
  • 53
  • 500
  • 612