Home > Software engineering >  Toggle /- in element on click
Toggle /- in element on click

Time:01-07

I have a table with expand and collapse already working, but I would like to add the and - buttons to make the functionality more dynamic. Can anyone help me with that?

$('tr.header').click(function() {
  $(this).nextUntil('tr.header').css('display', function(i, v) {
    return this.style.display === 'table-row' ? 'none' : 'table-row';
  });
});
tr {
  display: none;
}

tr.header {
  display: table-row;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="0">
  <tr >
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr >
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

http://jsfiddle.net/5cdh4L23/

CodePudding user response:

To do what you require you can add a span element to the .header cell to contain the or -. When the click occurs you can swap the characters over based on their current values.

Also note that you can use a CSS class to display the tr elements which makes the JS a little cleaner as you can use toggleClass() instead of a ternary in css().

$('tr.header').click(function() {
  $(this)
    .find('span').text((i, t) => t === ' ' ? '-' : ' ').end()
    .nextUntil('tr.header').toggleClass('show');
});
tr { display: none; }
tr.show { display: table-row; }
tr.header { display: table-row; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table border="0">
  <tr >
    <td colspan="2">Header <span> </span></td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr >
    <td colspan="2">Header <span> </span></td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

  •  Tags:  
  • Related