jrdev
jrdev

Reputation: 125

HTML show/hide parts of a table onclick of table headers

I have a nested HTML table. I would like to show parts of the nested table depending on the header clicked using javascript

http://jsfiddle.net/TtWTR/103/

so far it shows all three parts. I want to click header A and show only optionA, click headerB and only show optionB etc etc. Not sure if ive set it up right as all three are showing. thanks

Upvotes: 0

Views: 1020

Answers (3)

Chaitanya
Chaitanya

Reputation: 131

This can be done using the following script

        $('.nested').hide();
        $('tr .trigger').click(function() {
            var target_id= "#"+$(this).attr('id')+"-table";
            $('.nested').not(target_id).hide();
            $(target_id).show();
        });

and is shown in http://jsfiddle.net/TtWTR/152/

Upvotes: 0

Usually I find it convenient to use CSS class selectors on the "root" element (in your case that would be .toptable) allowing you to toggle it to show and hide child elements.

<table class="toptable">
    <tr class="accordion">
        <td class="A trigger">A</td>
        <td class="B trigger">B</td>
        <td class="C trigger">C</td>
    </tr>
    <tr>
        <td>
             <table>
                  <tr class="content A">
                      <!-- will toggle using show-A -->
                  </tr>
             </table
        </td>
    </tr>
</table>

Then you can make sure to hide the .content rows using CSS unless specific classes are set on the top table:

.content {
    display: none; /* content hidden by default */
}

.show-A .A.content {
    display: table; /* show when the parent table has .show-A set */
}

Now you just have to add event listeners to your triggers to toggle the classes for the different content rows:

const toptable = document.querySelector('.toptable');

['A', 'B', 'C'].forEach((group) => {
    const trigger = document.querySelector(`.${group}.trigger`);
    trigger.addEventListener('click', () => {
        toptable.classList.toggle(`show-${group}`);
    });
});

Upvotes: 0

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use below option oh hide() and show() methods

   $('.trigger').click(function() {
             console.log($(this).text())
      var selectedHdr = $(this).text();
      $('.nested tr').hide();
      $('.nested tr#'+selectedHdr).show();       
        });

https://codepen.io/nagasai/pen/vdabJQ

Upvotes: 1

Related Questions