Skip to content

Instantly share code, notes, and snippets.

@afbora
Last active February 12, 2019 10:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save afbora/6c98337a3455d45b6ae4e620d5cfbcf2 to your computer and use it in GitHub Desktop.
Save afbora/6c98337a3455d45b6ae4e620d5cfbcf2 to your computer and use it in GitHub Desktop.
Dynamic Colspan / Colspan All Columns on Bootstrap Sample
$(function() {
jQuery.fn.exists = function(){return this.length>0;}
// Dynamic Colspan
if($('[colspan="auto"]').exists())
{
$.each($('[colspan="auto"]'), function( index, value ) {
var table = $(this).closest('table'); // Get Table
var siblings = $(this).closest('tr').find('th:visible, td:visible').not('[colspan="auto"]').length; // Count colspan siblings
var numCols = table.find('tr').first().find('th:visible, td:visible').length; // Count visible columns
$(this).attr('colspan', numCols.toString()-siblings); // Update colspan attribute
});
}
});
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th class="hidden-xs">Birthdate</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="auto">Employers</th>
</tr>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td class="hidden-xs">1980</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
<td class="hidden-xs">1975</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
<td class="hidden-xs">1977</td>
</tr>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment