How to render columns in a table selectively

How to render columns in a table selectively. I have an HTML table containing columns (A, B, C, D, E) which are displayed by default.

I want the user to sub-filter this based on their selection (e.g. to show only A, D, E)

Is there a jQuery library to easily accomplish this setup?

+3


source to share


1 answer


Looking for something like this?



$('.column').on('change', function() {
  var index = $('th').index( $('th').filter('[data-column=' + $(this).data('column') + ']') );
  $('th,td').filter(function() {
    return $(this).index() === index;
  })[ this.checked ? 'show' : 'hide' ]();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>
    <input type="checkbox" class="column" checked data-column="a" name="a"/> A
  </label>
  <label>
    <input type="checkbox" class="column" checked data-column="b" name="b"/> B
  </label>
  <label>
    <input type="checkbox" class="column" checked data-column="c" name="c"/> C
  </label>
  <label>
    <input type="checkbox" class="column" checked data-column="d" name="d"/> D
  </label>
  <label>
    <input type="checkbox" class="column" checked data-column="e" name="e"/> E
  </label>
 </div>
  <table cellspacing="0" cellpadding="5" border="1">
    <tr>
      <th data-column="a">A</th>
      <th data-column="b">B</th>
      <th data-column="c">C</th>
      <th data-column="d">D</th>
      <th data-column="e">E</th>
    </tr>
    <tr>
      <td>some data</td>
      <td>some data</td>
      <td>some data</td>
      <td>some data</td>
      <td>some data</td>
    </tr>
  </table>
      

Run codeHide result


+2


source







All Articles