Click a button to display hidden rows

I would like to ask will it be possible that I have a table like this: JsFiddle

Expected result with Product BCD hidden:

<table>
  <th>
     Product Detail Display
  </th>
  <tr>
     <td> ----- Product A -----</td>
  </tr>
  <tr>
     <td>
       <div class="left">Total: 4 Product(s)</div>
       <div class="right"><button>View More Products</button></div>
     </td>
  </tr>
</table>

I want it initially will only display "Product A", and "Product B,C,D" will be three hidden rows. Until I click on the button "View More Products", the rows for "Product B,C,D" will be displayed. And the button will become "View Fewer Products" while the "Product B,C,D" will be hidden again...

I am not quite familiar with the table attribute such that I would like to ask whether it will be possible to do so? I am not sure the <td> attribute can deal with this... Or actually it will be better to use <div> and jQuery to control this action?

2 answers

  • answered 2017-06-17 18:58 Michael Coker

    Using CSS and jQuery you modify the $.text() of the button and on click add a class to the table that toggles the state and use CSS to hide/show the rows.

    var $table = $('table'),
    		$button = $('button');
    $button.on('click',function() {
    	if ($table.hasClass('more')) {
      	$table.removeClass('more');
      	$(this).text($(this).data('more'));
      } else {
      	$table.addClass('more');
      	$(this).text($(this).data('less'));
      }
    })
    td{
      text-align:center;
    }
    
    .left{
      width:50%;
      float:left;
    }
    
    .right{
      width:50%;
      float:right;
      text-align: right;
    }
    
    tr:nth-child(n + 3):not(:last-child) {
      display: none;
    }
    
    .more tr:nth-child(n + 3):not(:last-child) {
      display: table-row;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
    <tr>
      <th>
        Product Detail Display
      </th>
      </tr>
      <tr>
        <td> ----- Product A -----</td>
      </tr>
        <tr>
        <td> ----- Product B ----- </td>
      </tr>
        <tr>
        <td> ----- Product C ----- </td>
      </tr>
        <tr>
        <td> ----- Product D ----- </td>
      </tr>
      <tr>
        <td>
          <div class="left">Total: 4 Product(s)</div>
          <div class="right"><button data-less="View Less Products" data-more="View More Products">View More Products</button></div>
        </td>
      </tr>
    </table>

  • answered 2017-06-17 18:58 Diana Ysabel

    I updated your jsfiddle https://jsfiddle.net/6xfdez2x/1/

    Use a class to hide rows

    $('#more').on('click',function(){
        $("#tbl tr.occult").show();
      $(this).hide();
      $('#less').show();
    });
    
    $('#less').on('click',function(){
        $("#tbl tr.occult").hide();
      $(this).hide();
      $('#more').show();
    });