How to select lines from 1 to N above

Asked

Viewed 20 times

2

I have a dynamically generated table in the following scheme:

<table>
  <tr class="row-1">
    <td>A</td>
    <td>1</td>
  </tr>
  <tr class="row-2">
    <td>B</td>
    <td>2</td>
  </tr>
  <tr class="row-3">
    <td>C3</td>
    <td></td>
  </tr>
  <tr class="row-total">
    <td>
      <input type="button" value="Toogle">
    </td>
    <td>TOTAL</td>
  </tr>

  <tr class="row-1">
    <td>D</td>
    <td>4</td>
  </tr>
  <tr class="row-2">
    <td>E</td>
    <td>5</td>
  </tr>
  <tr class="row-3">
    <td>F</td>
    <td>6</td>
  </tr>
  <tr class="row-total">
    <td>
      <input type="button" value="Toogle">
    </td>
    <td>TOTAL</td>
  </tr>

</table>

In this table I will show only the line with the total value, and the previous ones will be hidden and will only be displayed by a toggle.

I must use the nth-child or there’s another way to do it?

  • What/what are the "total" lines you want to show? A + B or the sum from A to F ?

  • As TR with class="total" are the ones that will be visible, @Sergio. The TR previous will be hidden.

  • Only when any TOTAL is clicked, as TR previous to it will be displayed.

1 answer

2


You can use it like this:

$('input').on('click', function() {
    $(this).closest('tr').prevAll().each(function(){
        if (this.classList.contains('row-total')) return false;
        $(this).toggle();
    });
});

Using the .closest() you get the tr which contain the input clicked.

Using the .prevAll() you get all the tr previous.

Give away return false; inside a jQuery loop causes it to stop the loop, and therefore not go looking for the previous elements.

To hide everyone at the beginning is enough:

tr {
    display: none;
}
tr.row-total {
    display: block;
}

Example: https://jsfiddle.net/4t8obg8y/1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.