Check out this fiddle I created:
https://jsfiddle.net/desytec/m69q2xwr/34/
<style>
.table-scroll tbody {
position: absolute;
overflow-y: auto;
height: 250px;
}
</style>
<script>
var count = 0;
$(document).ready(function () {
$('#btnAdd').on('click', function() {
var tableBody = $('#mytable tbody');
var newRow =
'<tr id="tr_' + count + '">' +
'<td>Test Row ' + count + ' Col 1</td> ' +
'<td>Test Row ' + count + ' Col 2</td>'
'</tr>';
tableBody.append(newRow);
count++;
if (count == 3)
tableBody.addClass('table-scroll');
});
$('#btnDelete').on('click', function() {
var tableBody = $('#mytable tbody');
tableBody.children().last().remove();
count--;
if (count == 2)
tableBody.removeClass('table-scroll');
});
});
</script>
<div class="row">
<div class="row ml-4">
<button id="btnAdd" type="button" class="btn btn-secondary btn-circle m-4">Add row</button>
</div>
<div class="col-6">
<button id="btnDelete" type="button" class="btn btn-secondary btn-circle m-4">Delete row</button>
</div>
</div>
<table id="mytable" class="table table-striped dt-responsive w-100 table-bordered display nowrap table-hover mb-0">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I'm trying to implement a vertical scroll bar in the table body while keeping the header fixed when dynamically adding rows.
Despite my attempts, adding a class to the table body when reaching 3 rows does not seem to work for displaying the scrollbar. Any suggestions on the correct approach?
Thanks, Jaime