Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to select all table rows between two table rows in same table

Tags:

jquery

I have a table that has structure like this (td omitted)

<table>
<tr class="header">...</tr>
<tr class="row">...</tr>
<tr class="row">...</tr>
<tr class=="header">...</tr>
<tr class="row">...</tr>
<tr class="row">...</tr>
</table>

When user click on the row I need to hide all rows up to the next row that has class "header". What would be the easiest way to achieve this. Something along these lines, find all rows that have class header, find in the list row index of the clicked row, find the row index of the next row with the same class, and then select all rows within these two indicies?

like image 959
epitka Avatar asked Dec 23 '22 10:12

epitka


2 Answers

You could try something like:

$(document).ready($('table tr').click(
  function () {
    var tr = $(this).nextAll('tr');
    for (i = 0; i < tr.length; i++) {
      var class = $(tr[i]).attr('class');
      if (class == 'row')
        $(tr[i]).hide()
      else {
        if (class == 'header')
          return;
      }
    }
  }
));
like image 116
eKek0 Avatar answered Dec 24 '22 22:12

eKek0


You could just do:

$('table tr.row').hide();

Or if you have more than one separations like that:

$('table tr.header').click(function(){
    var rowsToHide = [];
    var trs = $('table tr');
    //let's get the index of the tr clicked first.
    var idx = trs.index(this);
    //now loop untill next header
    for(var i = idx+1; i < trs.length; i++){
        if(trs[i].attr('class') == 'row'){
            rowsToHide.push(trs[i]);
        } else {
            break;
        }
    }

    // now hide the array of row elements
    $(rowsToHide).hide();
})
like image 20
Dmitri Farkov Avatar answered Dec 25 '22 00:12

Dmitri Farkov