I’ve been working with an issue on my WordPress site for a bit now but I’m stuck. I have two working datatables (both showing on top of one another on the page currently) and a dropdown selection box. I need the dropdown box, which houses 2 options (one for each table) to select one table and show only that one.

Ideally I’d like the page to load with a default table (id=”mytable”) and then the dropdown can control everything from there.

Here is the code, other than the tables themselves:

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

//This is the code for the dropdown 

<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script>
(function($) {
$('#select-tables').on('change', function(){
   var table = $(this).find('option:selected');
   $('#' + table).show();
   $('table').not('#' + table).hide();
});
}(jQuery));

Both tables have their own datatable script:

//datatable 1, table id is mytable

<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();
   $('.dataTable').wrap('<div class="dataTables_scroll" />');
});
}(jQuery));
</script>

// table 2, table id is mytableSurvey
<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(){
$('#mytableSurvey').DataTable();
   $('.dataTable').wrap('<div class="dataTables_scroll" />');
});
}(jQuery));
</script>

Since this is in wordpress, I had to modify the JS for the dropdown code to match the datatable code so that it will work in WP. Is there a better way to code the dropdown with JS for existing datatables?

Read more here: Using dropdown to show 2 different datatables


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: