Hide only child rows

1

I have a table as follows:

<tabele>
   <thead>
      <tr>Codigo</tr>
   </thead>
    <tbody>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr>exemplo</tr>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr>exemplo</tr>
    <tbody>
</tabele>

I have a script done in JQuery that every click according to the class "click-show-hide-tr" it pops the next "tr" see the script below:

var toggleTable = (function () {
    var init = function(){
        $(".toggle-table tbody").on('click', '.click-show-hide-tr', function(){
        $(this).closest("tr").next().toggle();
        });
    };

    return {
        init:init
    }
})();

toggleTable.init();

I just want to hide all the secondary lines by clicking again on the first line without affecting the other lines that are hidden or not. Example:

<tabele>
   <thead>
      <tr>Codigo</tr>
   </thead>
    <tbody>
       /**
        * Essa é a linha Principal supondo que as linhas secundarias
        * estejam à mostra ao clicar nela de novo 
        * quero esconder todas elas sem afetar 
        * as outras linhas
        */
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr>exemplo</tr>

        /**
         * Esse é outra linha Principal com suas linhas secundarias
         * Não posso afetar nada daqui para baixo
         */
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr class='click-show-hide-tr'>exemplo</tr>
       <tr>exemplo</tr>
    <tbody>
</tabele>
    
asked by anonymous 25.11.2016 / 15:00

1 answer

1

Your selection is probably not working properly.

The .closest ("tr") function looks for the "tr" predecessor element, while .next () searches for all successor siblings, ie toggle is being applied to all rows below the items that have the '.click-show-hide-tr' class.

Example .next () : link

One way to work around this can be by adding a 'selected' class to the clicked item. From it you check which lines should be hidden. Try to do this:

$(".click-show-hide-tr").click(function(){

  // Se o item clicado nao estiver selecionado
  if(!$(this).hasClass("selecionado")) {

    // Adiciona a classe selecionado ao item
    $(this).addClass("selecionado");

    // Mostra as linhas secundarias apenas do item selecionado
    $(".click-show-hide-tr.selecionado").next().fadeIn();
  }	
  else {
    // Esconde as linhas secundarias apenas do item selecionado
    $(".click-show-hide-tr.selecionado").next().fadeOut();

    // Remove a classe selecionado do item
    $(this).removeClass("selecionado");
  }
});
    
26.11.2016 / 19:23