Datatables - Making the Javascript work
It took a little fiddling around in order to get datatables working.
The order of loading is very important. You can’t call something before it is loaded. I am by no means a javascript expert, but this seems to work for me - although the styling seems to be lacking a little bit:
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require datatables
//= require datatables/dataTables.bootstrap4
//= require turbolinks
//= require_tree .
$(document).on('turbolinks:load', function(){
$("table[role='datatable']").each(function(){
$(this).DataTable({
processing: true}); });
})
Important points to get it working:
- You will have to add a role tag to your table.
- You will need the thead and tbody tags.
- You will need the same number of td and th tags.
- If you don’t meet the above rules, it won’t work.
Here is a summarised example that works for me:
<table class="table thead-dark table-striped table-bordered table-hover table-responsive" summary="Quote list" role="datatable">
<thead>
<tr>
<th>Quote Number</th>
</tr>
</thead>
<tbody>
<% @quotes.each do |quote| %>
<tr class="<%= class_string(warning: quote.are_many_users?) %>">
<td><%= quote.id %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
(Please make not of the role attribute set to ‘datatable’ in the above).
Written on April 10, 2018