Create the footer in Data Table and to Export it with its footer into Excel and PDF - asp.net-core

I am trying to find the total of 'Net Value' and ' Total Value' in datatable as footer and the total value should be shown inside td element with the same alignment of its other data column. If I try to add footer , the total column shows different position from its data column also How can I find the total value and how to show it in footer row corresponding the column of its data row. Here is my code in html. Since I am not able to show the original program , I had to make it in presentable format. I am showing the data by calling JsonResult method from the controller , After fetching the data from the method and showing the report, the footer value will be showing bit far from its data column
#model myModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
</head>
<body>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>Item</td>
<td>NetVal</td>
<td>TotVal</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var report = {};
report.FromDate = "#Model.FromDate";
report.ToDate = "#Model.ToDate";
report.CustomerCode = "#Model.CustomerCode";
var table = $('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/mySales/SalesData",
"data": report,
"dataSrc": function (json) {
console.log(json);
return JSON.parse(json);
}
},
"columns": [
{ "data": "Item" },
{ "data": "NetVal" },
{ "data": "TotVal" },
],
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
},
{ "width": "10%", "targets": 0 },
{ "width": "5%", "targets": 1 },
{ "width": "5%", "targets": 2 },
],
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
$(api.column(2).footer()).html(col1);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
/
/ Controller
public JsonResult SalesData(myModel model)
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
{
fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
report.CustomerCode = "001";
var data = _unitOfWork.GetSummary(report.CustomerCode, fromDate, toDate);
String jsonResult = JsonConvert.SerializeObject(data);
return Json(jsonResult);
}

You could try scrollCollapse: true to set the footer to the right position,add a fallbackfunction to calculate the total value ,and check this demo related with export button if you missed to refer the js/css files
I tried as below:
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<div>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>AAA</td>
<td>200.00</td>
<td>300.00</td>
</tr>
<tr>
<td>BBB</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>CCC</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>DDD</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>EEE</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>FFF</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>GGG</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>HHH</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>III</td>
<td>300.00</td>
<td>200.00</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script>
$(document).ready(function () {
var table = $('#myTable').DataTable({
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
// Here you can add the rows
$(api.column(2).footer()).html(col2);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
The result:

Related

Loading the datatable with the data from JsonResult method from the controller, makes alignment fails in footer

I am trying to find the total of 'Net Value' and ' Total Value' in datatable as footer and the total value should be shown inside td element with the same alignment of its other data column. If I try to add footer , the total column shows different position from its data column. The footer should be showed the same column of its data. Here is my code in html. Since I am not able to show the original program , I had to make it in presentable format.
I am showing the data by calling JsonResult method from the controller , But after fetching the data from the Json method and showing the result in datatable with vertical scrolling, the footer value is showed bit far from its data column
#model myModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
</head>
<body>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>Item</td>
<td>NetVal</td>
<td>TotVal</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var report = {};
report.FromDate = "#Model.FromDate";
report.ToDate = "#Model.ToDate";
report.CustomerCode = "#Model.CustomerCode";
var table = $('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/mySales/SalesData",
"data": report,
"dataSrc": function (json) {
console.log(json);
return JSON.parse(json);
}
},
"columns": [
{ "data": "Item" },
{ "data": "NetVal" },
{ "data": "TotVal" },
],
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
},
{ "width": "10%", "targets": 0 },
{ "width": "5%", "targets": 1 },
{ "width": "5%", "targets": 2 },
],
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
$(api.column(2).footer()).html(col1);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
// Controller
public JsonResult SalesData(myModel model)
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
{
fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
report.CustomerCode = "001";
var data = _unitOfWork.GetSummary(report.CustomerCode, fromDate, toDate);
String jsonResult = JsonConvert.SerializeObject(data);
return Json(jsonResult);
}

How to change color of cell based on value in datatable [duplicate]

I am using DataTable to create an interactive table. I have 9 columns, 5 of which are values. I want to change the background color of each cell based on their specific.
I have started off trying to change the entire row color first as this seemed like an easier task. However I can't get anything to change.
My code is below:
<head>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function(){
$('#countryTable').DataTable();
});
</script>
<script>
$(document).ready( function () {
$('#countryTable ').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] > 11.7 )
{
$(nRow).css('color', 'red')
}
else if ( aData[2] == "4" )
{
$(nRow).css('color', 'green')
}
}
});
</script>
</head>
<body>
<table id ="countryTable" class="display" cellspacing="0" data-page-length='193'>
<thead>
<tr>
<th>Rank</th>
<th>Country</th>
<th>Code</th>
<th>Total</th>
<th>Beer</th>
<th>Wine</th>
<th>Spirits</th>
<th>Other</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Estonia</td>
<td>EE</td>
<td>14.97</td>
<td>5.87</td>
<td>1.65</td>
<td>5.64</td>
<td>1.81</td>
<td>3 - Medium Risky</td>
</tr>
<tr>
<td>2</td>
<td>Belarus</td>
<td>BY</td>
<td>14.44</td>
<td>2.5</td>
<td>0.75</td>
<td>6.73</td>
<td>4.46</td>
<td>4 - Very Risky</td>
</tr>
</tbody>
I have also tried using the following function but to no luck.
If anyone could help it would be greatly appreciated as I am very new to JavaScript.
$(document).ready( function () {
$('#countryTable').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] == "5" )
{
$('td', nRow).css('background-color', 'Red');
}
else if ( aData[3] == "4" )
{
$('td', nRow).css('background-color', 'Orange');
}
}
});
First of all, initialize DataTable only once. Then as per your question, use rowCallback and not fnRowCallBack as shown below:
var oTable = $('#countryTable').DataTable({
'rowCallback': function(row, data, index){
if(data[3]> 11.7){
$(row).find('td:eq(3)').css('color', 'red');
}
if(data[2].toUpperCase() == 'EE'){
$(row).find('td:eq(2)').css('color', 'blue');
}
}
});
Here's a fiddle

Datatables: Change cell color based on values

I am using DataTable to create an interactive table. I have 9 columns, 5 of which are values. I want to change the background color of each cell based on their specific.
I have started off trying to change the entire row color first as this seemed like an easier task. However I can't get anything to change.
My code is below:
<head>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function(){
$('#countryTable').DataTable();
});
</script>
<script>
$(document).ready( function () {
$('#countryTable ').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] > 11.7 )
{
$(nRow).css('color', 'red')
}
else if ( aData[2] == "4" )
{
$(nRow).css('color', 'green')
}
}
});
</script>
</head>
<body>
<table id ="countryTable" class="display" cellspacing="0" data-page-length='193'>
<thead>
<tr>
<th>Rank</th>
<th>Country</th>
<th>Code</th>
<th>Total</th>
<th>Beer</th>
<th>Wine</th>
<th>Spirits</th>
<th>Other</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Estonia</td>
<td>EE</td>
<td>14.97</td>
<td>5.87</td>
<td>1.65</td>
<td>5.64</td>
<td>1.81</td>
<td>3 - Medium Risky</td>
</tr>
<tr>
<td>2</td>
<td>Belarus</td>
<td>BY</td>
<td>14.44</td>
<td>2.5</td>
<td>0.75</td>
<td>6.73</td>
<td>4.46</td>
<td>4 - Very Risky</td>
</tr>
</tbody>
I have also tried using the following function but to no luck.
If anyone could help it would be greatly appreciated as I am very new to JavaScript.
$(document).ready( function () {
$('#countryTable').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] == "5" )
{
$('td', nRow).css('background-color', 'Red');
}
else if ( aData[3] == "4" )
{
$('td', nRow).css('background-color', 'Orange');
}
}
});
First of all, initialize DataTable only once. Then as per your question, use rowCallback and not fnRowCallBack as shown below:
var oTable = $('#countryTable').DataTable({
'rowCallback': function(row, data, index){
if(data[3]> 11.7){
$(row).find('td:eq(3)').css('color', 'red');
}
if(data[2].toUpperCase() == 'EE'){
$(row).find('td:eq(2)').css('color', 'blue');
}
}
});
Here's a fiddle

Data inserting using jquery, AJAX in ASP.NET MVC4?

I am trying to insert data to the database. For that I am using ajax and jquery, but the values from textbox are coming null and inserting the same in database. Here is the code of html markup and jQuery button click event handling:
#using (#Html.BeginForm("VewResult", "States" ))
{
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { ID = "txtStateid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { ID = "txtdistrictid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { ID = "txtStatendame", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
}
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#txtStateid').val();
var districtid = $('#txtdistrictid').val();
var statename = $('#txtStatendame').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
contentType: 'application/html; charset=utf-8',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
}
Please try below code.
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#StateID').val();
var districtid = $('#DistrictID').val();
var statename = $('#StateName').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
There is no need of form tag is required if you are calling as ajax. Or instead of jQuery ajax you can use Ajax.Beginform() . For this please refer
And your action will be
Public ActionResult VewResult(string stid,string districid,string stname)
{
//Your body
return;
}
Your are sending the data in HTML format to the Controller Action. Instead pass it as JSON. This link would be helpful to implement it.

How can we change width of search fields in DataTables

Can I change the width of search text fields in dataTables ?
I am writing following code right now but it is not working.
$('#example').dataTable()
.columnFilter({ sPlaceHolder: "head:before",
aoColumns: [ { type: "text",width:"10px" },
{ type: "date-range" },
{ type: "date-range" }
]
});
And if my dataTables is dynamically generated like as gven below:
$('#example').dataTable({
"aaData": aDataSet,
"aoColumns": [
{ "sTitle": "#","sWidth": "10px" },
{ "sTitle": "ID" },
{ "sTitle": "Staff Name" },
{ "sTitle": "Rig Days" },
{ "sTitle": "Manager"},
{ "sTitle": "Grade"},
{ "sTitle": "Tools"},
{ "sTitle": "Vacations"},
{ "sTitle": "Presently On"},
]
});
}
How to add Search field in this dynamically created DataTable to search by each column?
None of the above solution worked for me; then I got this:
$(document).ready(function () {
$('.dataTables_filter input[type="search"]').css(
{'width':'350px','display':'inline-block'}
);
});
And it worked perfectly!
If you want to place a placeholder too inside the search box use this ..
$('.dataTables_filter input[type="search"]').
attr('placeholder','Search in this blog ....').
css({'width':'350px','display':'inline-block'});
And this will work for sure.
To change the search box width, all I had to do was go into my .css file and enter the following:
.dataTables_filter input { width: 300px }
it's worked for me
<script>
var datatable = $('#table').DataTable({
...<datatables properties>,
initComplete: function () {
$('.dataTables_filter input[type="search"]').css({ 'width': '350px', 'display': 'inline-block' });
}
</script>
The only thing worked for me is this css.
$(document).ready(function(){
$('#datatable-buttons_filter').css({"position":"relative","left":"-100px"});
});
try to use css to change the width
example
.text_filter{
width:45%;
min-width:200px;
}
I applied this solution in my environment (Laravel 5.2, yajra/Laravel-DataTables 6.0, Bootstrap 3.x):
My table:
<table id="my-table" class="table table-striped table-hover" style="font-size: 80%">
<thead>
<tr>
<th class="input-filter" style="text-align:center;width: 5%">ID</th>
...
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th style="text-align:center;width: 5%">ID</th>
...
</tr>
</tfoot>
My script:
<script type="text/javascript">
var dt = $('#my-table').DataTable({
stateSave: true,
responsive: true,
processing: true,
serverSide: true,
order: [[ 0, "desc" ]],
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
ajax: {
url: '...',
},
columns: [
{data: 'id', name: 'id',orderable:true,searchable:true},
...
],
language: {
url: '....'
},
initComplete: function () {
this.api().columns('.input-filter').every(function () {
var column = this;
var input = document.createElement("input");
// start - this is the code inserted by me
$(input).attr( 'style', 'text-align: center;width: 100%');
// end - this is the code inserted by me
$(input).appendTo($(column.footer()).empty())
.on('keyup', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? val : '', true, true).draw();
});
});
}
});
</script>
here is the repeater
<asp:Repeater ID="rptClients" runat="server">
<HeaderTemplate>
<table id="example" class="display">
<thead>
<tr style="color:#fff;">
<th>Edit</th>
<th>Client Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Phone</th>
<th>Fax</th>
<th>Client Type</th>
<th>Active</th>
</tr>
<tr id="filterRow">
<td>Edit</td>
<td>Client Name</td>
<td>Address</td>
<td>City</td>
<td>State</td>
<td>Zip</td>
<td>Phone</td>
<td>Fax</td>
<td>Client Type</td>
<td>Active</td>
</tr>
</thead>
<tfoot style="display:none;">
<tr>
<td> </td>
</tr>
</tfoot>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><div class="padBtm-05 padTop-10"><asp:Button runat="server" ID="btnEdit" Text="Edit" /></div></td>
<td>
<%# Container.DataItem("ClientName")%>
</td>
<td>
<%# Container.DataItem("ClientAddress")%>
</td>
<td>
<%# Container.DataItem("ClientCity")%>
</td>
<td>
<%# Container.DataItem("State")%>
</td>
<td>
<%# Container.DataItem("ClientZip")%>
</td>
<td>
<%# Container.DataItem("ClientPhone")%>
</td>
<td>
<%# Container.DataItem("ClientFax")%>
</td>
<td>
<%# Container.DataItem("ClientType")%>
</td>
<td>
<%# Container.DataItem("Active")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
There are filters on all columns. Here I actually hide the edit column filter since it doesn't need one. If i don't render a filter for this column my filtering is off 1 column. In the javascript i target my table row which will end up being my title placeholder. Based on the placeholder name you can run an if statement that allows you to target the input element and set the width of the item. I have found setting the width of the filter sets the column width on the table.
// apply the input styling
$('#example thead td').each(function (i) {
var title = $('#example thead th').eq($(this).index()).text();
if (title == "Edit") {
var serach = '<input type="text" style="display:none;" placeholder="' + title + '" />';
} else if (title == "Client Name") {
var serach = '<input type="text" style="width:370px;" placeholder="' + title + '" />';
} else if (title == "Zip") {
var serach = '<input type="text" style="width:50px;" placeholder="' + title + '" />';
} else {
var serach = '<input type="text" placeholder="' + title + '" />';
}
$(this).html('');
$(serach).appendTo(this).keyup(function () { table.fnFilter($(this).val(), i) })
});
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
I have used the below code while using dataTables
JS
$('#du_ft_table').dataTable( { <br/>
"bProcessing": true,<br/>
"bServerSide": true,<br/>
scrollX: true,<br/>
"sAjaxSource": "../server_processing_man.php?sourceC=du_ft&rights=1&mandatory=1&retailer_id=2725",
"aoColumns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
{ "mData": function(obj) {
return '<a class="btn btn-xs btn-primary" href="EBSNL_NW='+obj[0]+'" alt="Edit" title="Edit"><i class="fa fa-pencil-square-o"></i></a>';
}}
]
} );
$('.dataTables_scrollFootInner tfoot th').each( function () {<br/>
var title = $(this).text();<br/>
if(title != '') $(this).html( '<input type="text" placeholder="Search '+title+'" />' );<br/>
});
var duft_table = $('#du_ft_table').DataTable();
// Apply the search
duft_table.columns().every( function () {<br/>
var that = this;<br/>
$( 'input', this.footer() ).on( 'keyup change', function () {<br/>
if ( that.search() !== this.value ) {<br/>
that.search(this.value).draw();<br/>
}<br/>
} );
});
Nativ javascript solution.
$(document).ready(function() {
$('#yourTableId').DataTable();
var addressTableFilter = document.getElementById('addressTable_filter');
addressTableFilter.firstChild.getElementsByTagName('input')[0].style.width = "400px";
addressTableFilter.firstChild.getElementsByTagName('input')[0].setAttribute('placeholder', 'Search');
addressTableFilter.firstChild.removeChild(document.getElementById('addressTable_filter').firstChild.firstChild);
});
Dont forget to wrap everything inside document ready(if u using it)otherwise other lines may kick in before datatable is initiated and you will get error.
This will also remove search label and add it as placeholder inside input box.