Datatables: how to get sort arrows on top - javascript

I’m using DataTables to display data in my UI.
I’ve configured it to show a search box for every column.
But now the sort arrows are not on the top any more.
How it is currently looking:
Image (I do not have enough reputation to post an image sry.)
How can I get them back to the top?
HTML:
<div id="container">
<div id="demo">
<h2>Index</h2>
<table id="example" class="display">
<thead>
<tr>
<th>MovieId</th>
<th>Title</th>
<th>TagLine</th>
<th>AirDate</th>
</tr>
<tr>
<td></td>
<td>Title</td>
<td>TagLine</td>
<td>AirDate</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
JS-Code:
$(document).ready(function () {
$('#example thead td').each(function () {
var title = $('#example thead td').eq($(this).index()).text();
if (title == "") {
return;
}
$(this).html('<input type="text" placeholder="SearchText ' + title + '" />');
});
var table = $('#example').DataTable({
"sAjaxSource": "http://localhost:51794/Movie/AjaxHandler",
"bProcessing": true,
"bServerSide": true,
"sDom": 'ltipr',
"aoColumns": [
{
"sName": "MovieId",
"bSortable": false,
"bSearchable": false,
"bVisible": false
},
{ "sName": "Title" },
{ "sName": "TagLine" },
{ "sName": "AirDate" }
]
});
$("#example thead input").on('keyup change', function () {
table
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
});

I suggest you to place the filters above header row, and your problem will be solved.
:
<thead>
<tr>
<td></td>
<td>Position</td>
<td>Office</td>
<td>Age</td>
<td>Start date</td>
<td>Salary</td>
</tr>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>

Add the option
"bSortCellsTop": true
to your datatables init code.
http://legacy.datatables.net/usage/options#bSortCellsTop

Related

How to hide table data upon load and only show table headers?

On my table page, I want to display only the header rather than the entire table at first.
Upon loading the page, I want to filter the data and display it based on the selected filter. Although the filter portion works, I am unable to figure out how to display only headers <thead> upon page load or when Select Location is selected from the dropdown.
Please see the sample code here: http://live.datatables.net/milazige/3/edit
$(document).ready(function () {
var table = $('#example').DataTable({
responsive: true,
paging: false,
searching: true,
lengthChange: false,
bInfo: false,
bSort: false,
order: []
});
$('#table-filter').on('change', function () {
table.search(this.value).draw();
});
});
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
</head>
<body>
<p>Select:
<select id="table-filter">
<option>Location</option>
<option>Dallax, TX</option>
<option>Boston, MA</option>
<option>Sandy, UT</option>
<option>Washington, DC</option>
<option>Omaha, NE</option>
</select>
</p>
<table id="example" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;">
<thead>
<tr>
<th>Location</th>
<th>Name</th>
<th>Job</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dallax, TX</td>
<td>test1</td>
<td>5</td>
<td>16</td>
</tr>
<tr>
<td>Boston, MA</td>
<td>test2</td>
<td>test2</td>
<td>test2</td>
</tr>
<tr>
<td>Sandy, UT</td>
<td>test3</td>
<td>test3</td>
<td>test3</td>
</tr>
<tr>
<td>Washington, DC</td>
<td>test4</td>
<td>test4</td>
<td>test4</td>
</tr>
<tr>
<td>Omaha, NE</td>
<td>test5</td>
<td>test5</td>
<td>test5</td>
</tr>
</tbody>
</table>
</body>
Hide the tbody on load using
window.onload = function () {
$('#example tbody').hide();
}
Whenever the user clicks on the filter options, display it. Modify the code inside $(document).ready(function () { ... })
$('#table-filter').on('change', function () {
$('#example tbody').show();
table.search(this.value).draw();
});
Hiding tbody in jQuery way
At the beginning of the script, hide the tbody and show it whenever the user clicks on a filter option
$(document).ready(function () {
// hide tbody on load
$('#example tbody').hide();
var table = $('#example').DataTable({
responsive: true,
paging: false,
searching: true,
lengthChange: false,
bInfo: false,
bSort: false,
order: []
});
$('#table-filter').on('change', function () {
// show the tbody when the user clicks on a filter option
$('#example tbody').show();
table.search(this.value).draw();
});
});

Cannot read property 'mData' of undefined - Datatables [duplicate]

I have an issue with Datatables. I also went through this link which didn't yield any results. I have included all the prerequisites where I'm parsing data directly into the DOM.
Script
$(document).ready(function() {
$('.viewCentricPage .teamCentric').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bPaginate": false,
"bFilter": true,
"bSort": true,
"aaSorting": [
[1, "asc"]
],
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0]
}, {
"bSortable": true,
"aTargets": [1]
}, {
"bSortable": false,
"aTargets": [2]
}],
});
});
FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead> and <tbody> tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here
A common cause for Cannot read property 'fnSetData' of undefined is the mismatched number of columns, like in this erroneous code:
<thead> <!-- thead required -->
<tr> <!-- tr required -->
<th>Rep</th> <!-- td instead of th will also work -->
<th>Titel</th>
<!-- th missing here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td>
<td>Titel</td>
<td>Missing corresponding th</td>
</tr>
</tbody>
While the following code with one <th> per <td> (number of columns must match) works:
<thead>
<tr>
<th>Rep</th> <!-- 1st column -->
<th>Titel</th> <!-- 2nd column -->
<th>Added th</th> <!-- 3rd column; th added here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td> <!-- 1st column -->
<td>Titel</td> <!-- 2nd column -->
<td>th now present</td> <!-- 3rd column -->
</tr>
</tbody>
The error also appears when using a well-formed thead with a colspan but without a second row.
For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript console:
<thead>
<tr>
<th>Rep</th>
<th>Titel</th>
<th colspan="5">Download</th>
</tr>
</thead>
While this works:
<thead>
<tr>
<th rowspan="2">Rep</th>
<th rowspan="2">Titel</th>
<th colspan="5">Download</th>
</tr>
<tr>
<th>pdf</th>
<th>nwc</th>
<th>nwctxt</th>
<th>mid</th>
<th>xml</th>
</tr>
</thead>
Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.
I had this same problem using DOM data in a Rails view created via the scaffold generator. By default the view omits <th> elements for the last three columns (which contain links to show, hide, and destroy records). I found that if I added in titles for those columns in a <th> element within the <thead> that it fixed the problem.
I can't say if this is the same problem you're having since I can't see your html. If it is not the same problem, you can use the chrome debugger to figure out which column it is erroring out on by clicking on the error in the console (which will take you to the code it is failing on), then adding a conditional breakpoint (at col==undefined). When it stops you can check the variable i to see which column it is currently on which can help you figure out what is different about that column from the others. Hope that helps!
This can also occur if you have table arguments for things like 'aoColumns':[..] which don't match the correct number of columns. Problems like this can commonly occur when copy pasting code from other pages to quick start your datatables integration.
Example:
This won't work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 1, 'desc' ]],
'aoColumns': [
null,
null,
null,
null,
null,
null,
{
'bSortable': false
}
]
});
</script>
But this will work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 0, 'desc' ]],
'aoColumns': [
null,
{
'bSortable': false
}
]
});
</script>
One more reason why this happens is because of the columns parameter in the DataTable initialization.
The number of columns has to match with headers
"columns" : [ {
"width" : "30%"
}, {
"width" : "15%"
}, {
"width" : "15%"
}, {
"width" : "30%"
} ]
I had 7 columns
<th>Full Name</th>
<th>Phone Number</th>
<th>Vehicle</th>
<th>Home Location</th>
<th>Tags</th>
<th>Current Location</th>
<th>Serving Route</th>
Tips 1:
Refer to this Link you get some Ideas:
https://datatables.net/forums/discussion/20273/uncaught-typeerror-cannot-read-property-mdata-of-undefined
Tips 2:
Check following is correct:
Please check the Jquery Vesion
Please check the versiion of yours CDN or your local datatable related .min & css files
your table have <thead></thead> & <tbody></tbody> tags
Your table Header Columns Length same like Body Columns Length
Your Using some cloumns in style='display:none' as same propery apply in you both Header & body.
your table columns no empty, use something like [ Null, --, NA, Nil ]
Your table is well one with out <td>, <tr> issue
You have to remove your colspan and the number of th and td needs to match.
I faced the same error, when tried to add colspan to last th
<table>
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
and solved it by adding hidden column to the end of tr
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
<!-- hidden column 4 for proper DataTable applying -->
<th style="display: none"></th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<!-- hidden column 4 for proper DataTable applying -->
<td style="display: none"></td>
</tr>
</tbody>
Explanaition to that is that for some reason DataTable can't be applied to table with colspan in the last th, but can be applied, if colspan used in any middle th.
This solution is a bit hacky, but simpler and shorter than any other solution I found.
I hope that will help someone.
in my case this error occured if i use table without header
<thead>
<tr>
<th>example</th>
</tr>
</thead>
I am getting a similar error. The problem is that the header line is not correct. When I did the following header line, the problem I was having was resolved.
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th colspan="6">Common Title</th>
</tr>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
</tbody>
</table>
Slightly different problem for me from the answers given above. For me, the HTML markup was fine, but one of my columns in the javascript was missing and didn't match the html.
i.e.
<table id="companies-index-table" class="table table-responsive-sm table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Created at</th>
<th>Updated at</th>
<th>Count</th>
</tr>
</thead>
<tbody>
#foreach($companies as $company)
<tr>
<td>{{ $company->id }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->created_at }}</td>
<td>{{ $company->updated_at }}</td>
<td>{{ $company->count }}</td>
</tr>
#endforeach
</tbody>
</table>
My Script:-
<script>
$(document).ready(function() {
$('#companies-index-table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: "{{ route('admincompanies.datatables') }}",
columns: [
{ name: 'id' },
{ name: 'name' },
{ name: 'created_at' },
{ name: 'updated_at' }, <-- I was missing this line so my columns didn't match the thead section.
{ name: 'count', orderable: false },
],
});
});
</script>
I had a dynamically generated, but badly formed table with a typo. I copied a <td> tag inside another <td> by mistake. My column count matched. I had <thead> and <tbody> tags. Everything matched, except for this little mistake I didn't notice for a while, because my column had a lot of link and image tags in it.
This one drove me crazy - how to render a DataTable successfully in a .NET MVC view. This worked:
**#model List<Student>
#{
ViewData["Title"] = "Index";
}
<h2>NEW VIEW Index</h2>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
#foreach (var element in Model)
{
<tr>
<td>#Html.DisplayFor(m => element.ID)</td>
<td>#Html.DisplayFor(m => element.FirstName)</td>
<td>#Html.DisplayFor(m => element.LastName)</td>
</tr>
}
</tbody>
</table>**
Script in JS file:
**$(document).ready(function () {
$('#example').DataTable();
});**
For those working in Webforms using GridView:
Moses's answer is totally correct. But since we're generating the table, the thead tag isn't generated by default. So to solve the problem add [YourGridViewID].HeaderRow.TableSection = TableRowSection.TableHeader to your backend, below of the DataBind() method call (if you're using it). This configuration takes the HeaderText value of the Field in your GridView as the value of the th tag it generates inside the thead.
In my case, and using ASP.NET GridView, UpdatePanel and with DropDownList (with Chosen plugin where I reset value to zero using a Javascript line), I got this error and tried everything with no hope for days. The problem was that the code of my dropdown in code behind was as follows and when I select a value twice to apply its action to selected grid rows I get that error. I thought for days it's a Javascript issue (again, in my case) and finally the fix was giving zero for the drowpdown value with the update process:
private void ddlTasks_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ddlTasks.SelectedValue != 0) {
ChangeStatus(ddlTasks.SelectedValue);
ddlTasks.SelectedValue = "0"; //// **This fixed my issue**
}
dvItemsGrid.DataSource = CreateDatasource();
dvItemsGrid.DataBind();
dvItemsGrid.UseAccessibleHeader = true;
dvItemsGrid.HeaderRow.TableSection = TableRowSection.TableHeader;
}
This was my fault:
$('#<%= DropDownList.ClientID%>').val('0').trigger("chosen:updated").chosen();
I had encountered the same issue but I was generating table Dynamically. In my case, my table had missing <thead> and <tbody> tags.
here is my code snippet if it helped somebody
//table string
var strDiv = '<table id="tbl" class="striped center responsive-table">';
//add headers
var strTable = ' <thead><tr id="tableHeader"><th>Customer Name</th><th>Customer Designation</th><th>Customer Email</th><th>Customer Organization</th><th>Customer Department</th><th>Customer ContactNo</th><th>Customer Mobile</th><th>Cluster Name</th><th>Product Name</th><th> Installed Version</th><th>Requirements</th><th>Challenges</th><th>Future Expansion</th><th>Comments</th></tr> </thead> <tbody>';
//add data
$.each(data, function (key, GetCustomerFeedbackBE) {
strTable = strTable + '<tr><td>' + GetCustomerFeedbackBE.StrCustName + '</td><td>' + GetCustomerFeedbackBE.StrCustDesignation + '</td><td>' + GetCustomerFeedbackBE.StrCustEmail + '</td><td>' + GetCustomerFeedbackBE.StrCustOrganization + '</td><td>' + GetCustomerFeedbackBE.StrCustDepartment + '</td><td>' + GetCustomerFeedbackBE.StrCustContactNo + '</td><td>' + GetCustomerFeedbackBE.StrCustMobile + '</td><td>' + GetCustomerFeedbackBE.StrClusterName + '</td><td>' + GetCustomerFeedbackBE.StrProductName + '</td><td>' + GetCustomerFeedbackBE.StrInstalledVersion + '</td><td>' + GetCustomerFeedbackBE.StrRequirements + '</td><td>' + GetCustomerFeedbackBE.StrChallenges + '</td><td>' + GetCustomerFeedbackBE.StrFutureExpansion + '</td><td>' + GetCustomerFeedbackBE.StrComments + '</td></tr>';
});
//add end of tbody
strTable = strTable + '</tbody></table>';
//insert table into a div
$('#divCFB_D').html(strDiv);
$('#tbl').html(strTable);
//finally add export buttons
$('#tbl').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
In addition to inconsistent and numbers, a missing item inside datatable scripts columns part can cause this too. Correcting that fixed my datatables search bar.
I'm talking about this part;
"columns": [
null,
.
.
.
null
],
I struggled with this error till I was pointed that this part had one less "null" than my total thead count.
in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
<th>heading 4</th>
<th>heading 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
<td>data-4</td>
<td>data-5</td>
</tr>
</tbody>
</table>
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
You need to wrap your your rows in <thead> for the column headers and <tbody> for the rows. Also ensure that you have matching no. of column headers <th> as you do for the td
I may be arising by aoColumns field. As stated HERE
aoColumns: If specified, then the length of this array must be equal
to the number of columns in the original HTML table. Use 'null' where
you wish to use only the default values and automatically detected
options.
Then you have to add fields as in table Columns
...
aoColumnDefs: [
null,
null,
null,
{ "bSortable": false },
null,
],
...
I found some "solution".
This code doesn't work:
<table>
<thead>
<tr>
<th colspan="3">Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
But this is ok:
<table>
<thead>
<tr>
<th colspan="2">Test</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
I think, that the problem is, that the last TH can't have attribute colspan.

DataTables selectall Checkbox in second page shows selected?

am working on Data Tables, here i have select all box checkbox in header, where i can select all tr elements when i click on that, here i have pagination, after selecting selectAll check box when i go to second page here in second page select all check is remains selected, but it shouldn't be in state of selected?
Here i want to checkall rows as per page only, but not in second page
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://api.myjson.com/bins/1us28',
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' +
$('<div/>').text(data).html() + '">';
}
}],
'order': [1, 'asc']
});
$('body').on('change', '#selectAllAgents', function() {
var rows, checked;
rows = $('#example').find('tbody tr');
checked = $(this).prop('checked');
$.each(rows, function() {
var checkbox = $($(this).find('td').eq(0)).find('input').prop('checked', checked);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<form id="frm-example" action="/path/to/your/script" method="POST">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th><input name="select_all" value="1" id="selectAllAgents" type="checkbox" /></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</form>
You can make the checkbox as unchecked on page change event.
Check the event on: https://datatables.net/reference/event/page Datatable Site.
Edit:
Changes made to save to select box value on each page change with a variable. so it will manage the check state on each page.
var pageChecked = [];
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://api.myjson.com/bins/1us28',
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' +
$('<div/>').text(data).html() + '">';
}
}],
'order': [1, 'asc']
});
$('#example').on( 'page.dt', function () {
var info = table.page.info();
var checked = false;
if(pageChecked[info.page])
{
checked = true;
}
$('#selectAllAgents').prop('checked', checked);
});
$('body').on('change', '#selectAllAgents', function() {
var rows, checked;
rows = $('#example').find('tbody tr');
checked = $(this).prop('checked');
var info = table.page.info();
pageChecked[info.page] = checked;
$.each(rows, function() {
var checkbox = $($(this).find('td').eq(0)).find('input').prop('checked', checked);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<form id="frm-example" action="/path/to/your/script" method="POST">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th><input name="select_all" value="1" id="selectAllAgents" type="checkbox" /></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</form>

How to make datatable footer appear on the print page

I have only seen two question here about this and it didnt work/ i didnt understand it. This is my table
<table class="table table-bordered make_datatable">
<thead>
<tr>
<th>SL No</th>
<th>Member Code</th>
<th>Name</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>11910</td>
<td>KRATOS</td>
<td>SH001</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="3" style="text-align:right">Grand Total:</th>
<th></th>
</tr>
</tfoot>
</table>
everything else is printing correctly and i have used the customize option to print the footer for now but i'd like to know how to print this along with the datatable, jquery for datatable:
var make_datatable = $('.make_datatable').DataTable( {
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0,
}],
"searching": false,
"order": [ 1, 'asc'],
dom: 'Blfrtip',
buttons: [
{
extend: 'print',
title : ' ',
text: '<i class="glyphicon glyphicon-print"></i><span>Print</span>',
className: 'btn btn-info printclass textSan' ,
customize: function ( win ) {
$(win.document.body)
.prepend(
'#include("report/memberreportheader")'
);
$(win.document.body)
.append(
'#include("report/shop/printmemberconsolidate")'
)
}
},
],
});
solved it by using footer: true and removed the colspan and added th to match other rows
buttons: [
{
extend: 'print',
footer: true,
title: ' ',
text: '<i class="glyphicon glyphicon-print"></i><span>Print</span>',
className: 'btn btn-info printclass textSan',
customize: function (win) {
$(win.document.body)
.prepend(
'#include("report/memberreportheader")'
);
}
},
]
HTML:
<tr>
<th></th>
<th></th>
<th></th>
<th>Grand Total:</th>
<th>{{$total}}</th>
<th>--</th>
</tr>

How limit jquery data Table field from showing all column in MVC view

I am using jquery DataTable in this link to create a grid in MVC to show some data and show and hide the column.
https://datatables.net/examples/api/show_hide.html
I am showing all the column and then show and hide base on what column user choose. But I like to show just 5 column at beginning in my grid instead of all column and user able to show/ hide the rest.
I am not sure how to do that.
This is my code:
this is jquery code to show/hide the column:
$(document).ready(function () {
var table = $('#DataLegal').DataTable({
"paging": true
});
$('a.toggle-vis').on('click', function (e) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
//Get the column API object
var column = table.column($(this).attr('data-column'));
// Toggle the visibility
column.visible(!column.visible());
});
var ms = $('#magicsuggest').magicSuggest({
// Converts our C# object in a JSON string.
data: #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(columns))
});
$(ms).on('selectionchange', function(e,m){
// Turn on ALL columns... Like a reset...
$.each(table.columns()[0], function(index) {
table.column(index).visible(true);
});
// Turn off each column in the value array... Value = int[0, 1, 2, ...]
$.each(this.getValue(), function(index, item) {
table.column(item).visible(false);
});
});
});
and this is my grid that is showing all the column. I like to limit this at first show only 5 column:
//This is when user sees the column name to show/hide
<div id="content">
<table>
<tr>
<td>
<div id="magicsuggest"></div>
</td>
<td id="returnS5"></td>
</tr>
</table>
</div>
//This is the grid that I have all the column and I like to limit it to 5 column
<br />
<table width="100%" class="display" id="DataLegal" cellspacing="0">
<thead>
<tr>
<th>Entity</th>how hide some column
<th>License Type</th>
<th>State</th>
<th>Location</th>
<th>Data User</th>
<th>Create Date</th>
<th>Modified Date</th>
<th>Modified By</th>
<th>Status</th>
<th>Surrender Effective Date</th>
<th>NMLS</th>
<th>License Name</th>
<th>License Number</th>
<th>Issuance Date</th>
<th>Expiration Date</th>
<th>License Renewal Due Date</th>
<th>License Renewal Fee</th>
<th>License Renewal Filed Date</th>
<th>Annual Report Due Date</th>
<th>Annual Report Filed Date</th>
<th>Other Filed Date</th>
<th>Display</th>
<th>Display Comments</th>
<th>Regulator</th>
<th>Governing Law</th>
<th>Regulator Address</th>
<th>License Restrictions</th>
<th>Additional Notes</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>#item.Entity</td>
<td>#item.License_Type</td>
<td>#item.State</td>
<td>#item.Location</td>
<td>#item.dataUser</td>
<td>#item.Create_Date</td>
<td>#item.Modified_Date</td>
<td>#item.Modified_By</td>
<td>#item.Status</td>
<td>#item.Surrender_Effective_Date</td>
<td>#item.NMLS</td>
<td>#item.License_Name</td>
<td>#item.License_Number</td>
<td>#item.Issuance_Date</td>
<td>#item.Expiration_Date</td>
<td>#item.License_Renewal_Due_Date</td>
<td>#item.License_Renewal_Fee</td>
<td>#item.License_Renewal_Filed_Date</td>
<td>#item.Annual_Report_Due_Date</td>
<td>#item.Annual_Report_Filed_Date</td>
<td>#item.Other_Filed_Date</td>
<td>#item.Display</td>
<td>#item.Display_Comments</td>
<td>#item.Regulator</td>
<td>#item.Governing_Law</td>
<td>#item.Regulator_Address</td>
<td>#item.License_Restrictions</td>
<td>#item.Additional_Notes</td>
</tr>
}
</tbody>
</table>
The initial visibility of columns is an initialization option which can be set in the columnDefs property. Example:
"columnDefs": [
{
"targets": [ 2 ],
"visible": false,
"searchable": false
}]
Reference:
Hidden Columns

Categories

Resources