Tom N. Tom N. - 1 year ago 48
Javascript Question

Datatables - showing/hiding with select box

I currently have 2 working datatables and a select box. Currently, they both show up on page load, and then if I select one from the select box it shows that one and hides the other. The select box works great from there, but I'd like to show just one table on page load by default, rather than both.

Here is the datatable script with select box code:

<select name='tables' id='select-tables'>
<option value="mytable">Survey Test Table</option>
<option value="mytableSurvey">Survey Only</option>
</select>
</br>

<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function() {
$('#mytable').DataTable();
$('#mytableSurvey').DataTable();
$('.dataTable').wrap('<div class="dataTables_scroll" />');

// select change event
$(document).on('change' , '#select-tables', function(){
var table = $(this).val();
$('#' + table +'_wrapper').show();
$('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
}).change();
});
}(jQuery));
</script>


Obviously, my table IDs are mytable and mytableSurvey so I won't post any of my actual table code, as everything necessary is in the datatable script here.

Everything here works, I'm just hoping to find an addition to this code that will only show 'mytable' on page load.

Answer Source

Try this code:

$(document).ready(function() {
    $('#mytable').DataTable();
    $('#mytableSurvey').DataTable();

    $(document).on('change' , '#select-tables', function(){
 var table = $(this).val();
 $('#' + table +'_wrapper').show();
 $('[id$="_wrapper"]').not('#' + table +'_wrapper').hide();
});
$("#select-tables").trigger("change");
});

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download