Home > Enterprise >  how to create dropdown to increase number of rows in html table to display using jquery
how to create dropdown to increase number of rows in html table to display using jquery

Time:12-19

<select>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">20</option>
</select>


<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

//jquery
var $rows=$("table tbody tr").length;

what I want is to allow user to select to display more rows if there is and also have 10 rows as default in the table if more than 10 rows is present

CodePudding user response:

Use slice(option-start, option-end) to show / hide desire table row when drop down change.

Example:

var deault_value = 1; // in your case default value is 10
var $rows = $("table tbody tr")
var $fotter = $("table tfoot tr")
$rows.hide();
$fotter.hide(); // if needed show footer , it's depend upon how you calculate summ
$rows.slice(0, 1).show(); // in your case show by default 10

$("select").change(function() {
  var num = $(this).val();
  $rows.hide();
  $($rows).slice(0, num * deault_value).show();
// Show fotter with calculation if needed. 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="1">1</option>
  <option value="2">2</option>

</select>


<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

CodePudding user response:

Maybe a jQuery plugin like DataTables can help you.

  • Related