I'm working on expand/collapse row functionality using jquery. It seems that it can find the table row I'm looking for and hides it by default. But then I'm trying to add expand/collapse functionality and looks like I can't access the right tag.

I got the jquery code from one of the other examples on the website. It's my first time working with it so I struggled with understanding other answers on the same topic.

I also think it was a bad idea to put the parent row and the one that is supposed to show/hide on the same level so any recommendation on that would be nice.

$(function() {
  $(".table-container__table").find(".expandable").hide();
  $(".table-container__table").click(function(event) {
    event.stopPropagation();
    var $target = $(event.target);
    if ($target.closest("td").attr("colspan") == 6) {
      $target.slideUp();
    } else {
      $target.closest("tr").next().find(".details-table__details-row").slideToggle();
    }
  });
});

Here is the jsfiddle with the full example: https://jsfiddle.net/in43sh/whs0e3fr/16/

1 Answers

1
mark.hch On Best Solutions

Per our comment discussion - the main issue (aside from .next to .next()) was that the parent row was hidden first, then a child row was shown - but the parent was still invisible. To resolve, just toggle the same thing that's hidden. Here's the applicable JS with comments:

//hide any ".expandable" rows
$(".table-container__table").find(".expandable").hide();

//whenever the table is clicked, check if the target was 
//within an ".expandable" row if it was, then slideToggle 
//that row, otherwise, if the next row is ".expandable", 
//slideToggle it instead
$(".table-container__table").click(function(event) {
  event.stopPropagation();
  var $target = $(event.target);
  if($target.closest('.expandable').length == 1) {
    $target.closest('.expandable').slideToggle();
  }
  else {
    if($target.closest('tr').next().hasClass('expandable')) {
      $target.closest('tr').next().slideToggle();
    }
  }
});