How to give a Confirmation Message on Datatable Page Navigation using jQuery? - javascript

I'm working on Asp .net MVC3.I'm using html table to display the table in front end.and i'm using datatable plugin for pagination,sorting and filtering.when user selects 2 records on page 1 and navigating to the next page confirmation box has to show as 'do you want to submit the selected values?' if the user clicks ok navigation has to be done otherwise it should remain on page1.Following is my table,
<table id="myIndiaTable">
<thead>
<th>Select All<input type="checkbox" class="chkheadind" onchange="Getchecked()" /></th>
#foreach (var item in Model.colName)
{
<th>#item.column_name</th>
}
</thead>
<tbody>
#foreach (var item in Model.bgv)
{
<tr>
<td><input type="checkbox" class="chkdataind"/></td>
<td id ="AsscId">#item.AsscID</td>
<td id ="AsscName">#item.AsscName</td>
<td>#Html.DropDownList("Education", new SelectList(Model.dd, "Validation_Code", "Validation_Status", #item.Education),new { style = "width: 80px;" })</td>
<td>#Html.DropDownList("Employment", new SelectList(Model.dd, "Validation_Code", "Validation_Status", #item.Employment),new { style = "width: 100px;" })</td>
<td>#Html.DropDownList("Criminal", new SelectList(Model.dd, "Validation_Code", "Validation_Status", #item.Criminal),new { style = "width: 80px;" })</td>
<td>#Html.DropDownList("DatabaseTest", new SelectList(Model.dd, "Validation_Code", "Validation_Status", #item.DatabaseTest),new { style = "width: 100px;" })</td>
</tr>
}
</tbody>
</table>
Following is the jquery,
<script type="text/javascript">
$("#myIndiaTable").dataTable({
"bFilter":true,
"bSort": true,
"bPaginate": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"bStateSave": true,
"bProcessing": true,
"bDeferRender":true
});
</script>

I have used
"fnDrawCallback": function (oSettings) {
}
to reinitialize something whenever the table is drawn again (its not only in the pagination case). This may not suit your case.
For pagination, the documentation suggest to use
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
// check what you want
// return true or false. true is expected to paginate and false is expected not to paginate
}

Related

How to set SeverSide in dynamic column in jquery datacolumn?

I have created a data table for the dynamic column and here is the code for the data table.
<table id="tag" class="display table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
#foreach (var item in Model.Select((value, i) => new { i, value}))
{
<th id=#(item.i+1)>#item.value.Category</th>
}
<th id="#(Model.Count()+1)">Simulation Name</th>
<th id="#(Model.Count()+2)">Patient Name</th>
</tr>
</thead>
</table>
and the javascript code for the dynamic data table is
$(document).ready(function () {
$("#tag").DataTable({
"aLengthMenu": [[5,10, 25, 50, 75, -1], [5,10, 25, 50, 75, "All"]],
"iDisplayLength": 5,
serverSide: true,
stateSave: true,
search: true,
ajax: {
type: 'POST',
dataType: 'json',
url: 'GetFilteredPatientTagss',
success: function (d) {
for (var i = 0; i < d.requestedRecords.length; i++) {
var result = Object.values(d.requestedRecords[i]);
$('#tag').DataTable().row.add(result).draw(false);
}
}
}
});
});
Here I have done serverSide is true, If I set server-side: false then the dataTable is fine, and search, dropdown and pagination are all from the client-side, but when I set serverSide: true it goes for infinite loop in the API and no data is displayed in the data table. I need to search and paginate in the data table from the server-side in this dynamic column(where there is no fixed number of columns). How Can I do this?

How to use a DataTable with an array of objects?

I'm trying to use the property "data" to show my data in the table, but the table doesn't works. I made a test using a local array of strings and works very well, I don't know why with an object the table doesn't works
ngAfterViewInit() {
this.listarNotificacao()
$('#datatables').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
lengthChange: false,
responsive: true,
searching: true,
data: this.notificacoes,
columns: [{
data: 'guidNotificacao'
},
{
data: 'titulo'
},
{
data: 'descricao'
},
{
data: 'escopo'
},
],
language: {
search: "_INPUT_",
searchPlaceholder: "Pesquisar promoções",
},
}
});
const table = $('#datatables').DataTable();
$('#inputSearch').on('keyup', function() {
table.search(this.value).draw();
});
}
<div class="material-datatables">
<table id="datatables" class="table table-no-bordered " cellspacing="0" width="100%" style="width:100%">
<thead>
<tr>
<th>#</th>
<th>Título</th>
<th>Descrição</th>
<th>Escopo</th>
</tr>
</thead>
</table>
</div>
You have a typo in your datatable initialization. There's an extra curly brace after language. If you look at your browser's dev console, it would have told you this.

DataTable : Hide data as default

I want to hide my data as default, and show the results if something in my Search Box.
Here is my current setting :
<script type="text/javascript">
$( document ).ready(function() {
$('#inventory').dataTable({
"lengthMenu": [ [5], [10, 25, 50, "All"] ],
"bLengthChange": false,
"search": {
"caseInsensitive": true
}
});
var dataTable = $('#inventory').dataTable();
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
});
</script>
Can you search some non-existent value (is there is any) just after creation of datatable like this.
$('#inventory').dataTable({
"lengthMenu": [ [5], [10, 25, 50, "All"] ],
"bLengthChange": false,
"search": {
"caseInsensitive": true
}
});
var dataTable = $('#inventory').dataTable();
dataTable.fnFilter('some non existant value');
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
});
First, wrap a <div> around my table and give it an id = main
<div id="main">
<table class="display" id="inventory">
<thead class="thin-border-bottom ">
<th>SKU</th>
<th>Description</th>
<th>Stock</th>
</thead>
<tbody>
#foreach ( Inventory::all() as $inventory)
<tr>
<td>{{ $inventory->sku }} </td>
<td>{{ $inventory->description }} </td>
<td>{{ $inventory->stock }} </td>
</tr>
#endforeach
</tbody>
</table>
</div>
Second, fix my script to hide that div, and only show it when there is something in the search box.
$('#main').hide();
// Setting to Inventory Table
$('#inventory').dataTable({
"lengthMenu": [ 10 ] ,
"bLengthChange": false,
});
// Bind the value from a new search to the dataTable
var dataTable = $('#inventory').dataTable();
$("#searchbox").keyup(function() {
dataTable.fnFilter(this.value);
$('#main').show(); // show the main div
});

DataTables: Add option on which script to run

I am showing a DataTables using the below code. It is using server side processing and works ok.
I would like to add a drop down option above the table with for example:
Product Group 1
Product Group 2
and then based on the selected option this determines what server side processing script is run.
Existing code
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var table = $('#table').dataTable( {
"ajax": {
"url": "../server_processing/prices.php",
"type": "POST"
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"order": [[ 1, "asc" ]],
"serverSide": true
} );
var tabletools = new $.fn.dataTable.TableTools( table, {
"dom": 'T<"clear">lfrtip',
"sSwfPath": "../copy_csv_xls_pdf.swf"
} );
$( tabletools.fnContainer() ).insertBefore('div.dataTables_wrapper');
} );
</script>
For example here the "url": "../server_processing/prices.php",would be "url": "../server_processing/prices.php?ProductGroup=X",.
I'm sure something like this is simple in JavaScript/jQuery but I'm not sure how to start. I am new to both, my only experience thus far has been DataTables.
Also how would I handle the HTML table itself as the column headers could change based on the selected product group.
Existing code
<table id="table" class="table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Price Table</th>
<th>Product Code</th>
<th>Product Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
this is correct for Product Group 1, but Product Group 2 might require an additional column header for example.
I understand the easier option is to just create 2 pages and have 2 tables but I don't want that.
I hope I've explained clearly enough, if more details are needed etc. I can help. Appreciate any help from the experts!
Try this : You can use fnReloadAjax as shown below
HTML -
<select id="select1">
<option value="1">Product Group 1</option>
<option value="2">Product Group 2</option>
</select>
jQuery :
$(document).ready(function() {
var table = $('#table').dataTable( {
"ajax": {
"url": "../server_processing/prices.php",
"type": "POST"
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"order": [[ 1, "asc" ]],
"serverSide": true
} );
var tabletools = new $.fn.dataTable.TableTools( table, {
"dom": 'T<"clear">lfrtip',
"sSwfPath": "../copy_csv_xls_pdf.swf"
} );
$( tabletools.fnContainer() ).insertBefore('div.dataTables_wrapper');
//on change event handle for select box
$('#select1').on("change", function(){
var value = $(this).val();
table.fnReloadAjax( '../server_processing/prices.php?ProductGroup='+value );
});
} );

Disable sorting for a particular column in jQuery DataTables

I am using the jQuery DataTables plugin to sort the table fields. My question is: how do I disable sorting for a particular column? I have tried with the following code, but it did not work:
"aoColumns": [
{ "bSearchable": false },
null
]
I have also tried the following code:
"aoColumnDefs": [
{
"bSearchable": false,
"aTargets": [ 1 ]
}
]
but this still did not produce the desired results.
This is what you're looking for:
$('#example').dataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 1 ] }
]
});
As of DataTables 1.10.5 it is now possible to define initialisation
options using HTML5 data-* attributes.
-from DataTables example - HTML5 data-* attributes - table options
So you can use data-orderable="false" on the th of the column you don't want to be sortable. For example, the second column "Avatar" in the table below will not be sortable:
<table id="example" class="display" width="100%" data-page-length="25">
<thead>
<tr>
<th>Name</th>
<th data-orderable="false">Avatar</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td><img src="https://www.gravatar.com/avatar/8edcff60cdcca2ad650758fa524d4990?s=64&d=identicon&r=PG" alt="" style="width: 64px; height: 64px; visibility: visible;"></td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td><img src="https://www.gravatar.com/avatar/98fe9834dcca2ad650758fa524d4990?s=64&d=identicon&r=PG" alt="" style="width: 64px; height: 64px; visibility: visible;"></td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
...[ETC]...
</tbody>
</table>
See a working example at https://jsfiddle.net/jhfrench/6yxvxt7L/.
To make a first column sorting disable, try with the below code in datatables jquery. The null represents the sorting enable here.
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false },
null,
null,
null
]
} );
Disable Sorting on a Column in jQuery Datatables
Using Datatables 1.9.4 I've disabled the sorting for the first column with this code:
/* Table initialisation */
$(document).ready(function() {
$('#rules').dataTable({
"sDom" : "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType" : "bootstrap",
"oLanguage" : {
"sLengthMenu" : "_MENU_ records per page"
},
// Disable sorting on the first column
"aoColumnDefs" : [ {
'bSortable' : false,
'aTargets' : [ 0 ]
} ]
});
});
EDIT:
You can disable even by using the no-sort class on your <th>,
and use this initialization code:
// Disable sorting on the no-sort class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "no-sort" ]
} ]
EDIT 2
In this example I'm using Datables with Bootstrap, following an old blog post. Now there is one link with updated material about styling Datatables with bootstrap.
What I use is just add a custom attribute in thead td and control sorting by checking that attr value automatically.
So the HTML code will be
<table class="datatables" cellspacing="0px" >
<thead>
<tr>
<td data-bSortable="true">Requirements</td>
<td>Test Cases</td>
<td data-bSortable="true">Automated</td>
<td>Created On</td>
<td>Automated Status</td>
<td>Tags</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>
And JavaScript for initializing datatables will be
(it will dynamically get the sorting information from table iteself ;)
$('.datatables').each(function(){
var bFilter = true;
if($(this).hasClass('nofilter')){
bFilter = false;
}
var columnSort = new Array;
$(this).find('thead tr td').each(function(){
if($(this).attr('data-bSortable') == 'true') {
columnSort.push({ "bSortable": true });
} else {
columnSort.push({ "bSortable": false });
}
});
$(this).dataTable({
"sPaginationType": "full_numbers",
"bFilter": bFilter,
"fnDrawCallback": function( oSettings ) {
},
"aoColumns": columnSort
});
});
columnDefs now accepts a class. I'd say this is the preferred method if you'd like to specify columns to disable in your markup:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th class="datatable-nosort">Actions</th>
</tr>
</thead>
...
</table>
Then, in your JS:
$("table").DataTable({
columnDefs: [{
targets: "datatable-nosort",
orderable: false
}]
});
Here is what you can use to disable certain column to be disabled:
$('#tableId').dataTable({
"columns": [
{ "data": "id"},
{ "data": "sampleSortableColumn" },
{ "data": "otherSortableColumn" },
{ "data": "unsortableColumn", "orderable": false}
]
});
So all you have to do is add the "orderable": false to the column you don't want to be sortable.
$("#example").dataTable(
{
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0, 1, 2, 3, 4, 5]
}]
}
);
For Single column sorting disable try this example :
<script type="text/javascript">
$(document).ready(function()
{
$("#example").dataTable({
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 0 ] }
]
});
});
</script>
For Multiple columns try this example: you just need to add column number. By default it's starting from 0
<script type="text/javascript">
$(document).ready(function()
{
$("#example").dataTable({
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 0,1,2,4,5,6] }
]
});
});
</script>
Here only Column 3 works
As of 1.10.5, simply include
'orderable: false'
in columnDefs and target your column with
'targets: [0,1]'
Table should like like:
var table = $('#data-tables').DataTable({
columnDefs: [{
targets: [0],
orderable: false
}]
});
If you set the FIRST column orderable property to false, you must also set the default order column otherwise it won't work since first column is the default ordering column. Example below disables sorting on first column but sets second column as default order column (remember dataTables' indexes are zero based).
$('#example').dataTable( {
"order": [[1, 'asc']],
"columnDefs": [
{ "orderable": false, "targets": 0 }
]
} );
To update Bhavish's answer (which I think is for an older version of DataTables and didn't work for me). I think they changed the attribute name. Try this:
<thead>
<tr>
<td data-sortable="false">Requirements</td>
<td data-sortable="false">Automated</td>
<td>Created On</td>
</tr>
</thead>
<tbody>
<tr>
<td>
"aoColumnDefs" : [
{
'bSortable' : false,
'aTargets' : [ 0 ]
}]
Here 0 is the index of the column, if you want multiple columns to be not sorted, mention column index values seperated by comma(,)
Using class:
<table class="table table-datatable table-bordered" id="tableID">
<thead>
<tr>
<th class="nosort"><input type="checkbox" id="checkAllreInvitation" /></th>
<th class="sort-alpha">Employee name</th>
<th class="sort-alpha">Send Date</th>
<th class="sort-alpha">Sender</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="userUid[]" value="{user.uid}" id="checkAllreInvitation" class="checkItemre validate[required]" /></td>
<td>Alexander Schwartz</td>
<td>27.12.2015</td>
<td>dummy#email.com</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$('#tableID').DataTable({
'iDisplayLength':100,
"aaSorting": [[ 0, "asc" ]],
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['nosort']
}]
});
});
</script>
Now you can give "nosort" class to <TH>
This works for me for a single column
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false
}]});
If you already have to hide Some columns, like I hide last name column. I just had to concatenate fname , lname , So i made query but hide that column from front end. The modifications in Disable sorting in such situation are :
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 3 ] },
{
"targets": [ 4 ],
"visible": false,
"searchable": true
}
],
Notice that I had Hiding functionality here
"columnDefs": [
{
"targets": [ 4 ],
"visible": false,
"searchable": true
}
],
Then I merged it into "aoColumnDefs"
Use the following code to disable ordering on first column:
$('#example').dataTable( {
"columnDefs": [
{ "orderable": false, "targets": 0 }
]
} );
To disable default ordering, you can also use:
$('#example').dataTable( {
"ordering": false,
} );
There are two ways, one is defined in html when you define table headers
<thead>
<th data-orderable="false"></th>
</thead>
Another way is using javascript, for example, you have table
<table id="datatables">
<thead>
<tr>
<th class="testid input">test id</th>
<th class="testname input">test name</th>
</thead>
</table>
then,
$(document).ready(function() {
$('#datatables').DataTable( {
"columnDefs": [ {
"targets": [ 0], // 0 indicates the first column you define in <thead>
"searchable": false
}
, {
// you can also use name to get the target column
"targets": 'testid', // name is the class you define in <th>
"searchable": false
}
]
}
);
}
);
you can also use negative index like this:
$('.datatable').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ -1 ] }
]
});
The code will look like this:
$(".data-cash").each(function (index) {
$(this).dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"bSort": false,
"aaSorting": []
});
});
Here is the answer !
targets is the column number, it starts from 0
$('#example').dataTable( {
"columnDefs": [
{ "orderable": false, "targets": 0 }
]
} );
You can directry use .notsortable() method on column
vm.dtOpt_product = DTOptionsBuilder.newOptions()
.withOption('responsive', true)
vm.dtOpt_product.withPaginationType('full_numbers');
vm.dtOpt_product.withColumnFilter({
aoColumns: [{
type: 'null'
}, {
type: 'text',
bRegex: true,
bSmart: true
}, {
type: 'text',
bRegex: true,
bSmart: true
}, {
type: 'text',
bRegex: true,
bSmart: true
}, {
type: 'select',
bRegex: false,
bSmart: true,
values: vm.dtProductTypes
}]
});
vm.dtColDefs_product = [
DTColumnDefBuilder.newColumnDef(0), DTColumnDefBuilder.newColumnDef(1),
DTColumnDefBuilder.newColumnDef(2), DTColumnDefBuilder.newColumnDef(3).withClass('none'),
DTColumnDefBuilder.newColumnDef(4), DTColumnDefBuilder.newColumnDef(5).notSortable()
];
set class "no-sort" in th of the table
then add css
.no-sort { pointer-events: none !important; cursor: default !important;background-image: none !important; }
by this it will hide the arrow updown and disble event in the head.

Categories