Related
I'd want to display result by column dropdown filter. But after choose table doesn't update result.
My main goal is filter by "Компания" column and that selector must be on top of the table.
`
$(document).ready(function() {
var exampleDataTable = $('#example').DataTable({
responsive: true,
colReorder: true,
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
language: {
buttons: {
colvis: 'Отображение столбцов'
},
"processing": "Подождите...",
"search": "Поиск:",
"lengthMenu": " _MENU_ ",
"info": "Показано с _START_ до _END_ записей из _TOTAL_",
"infoEmpty": "Записи с 0 до 0 из 0 записей",
"infoFiltered": "(отфильтровано из _MAX_ записей)",
"infoPostFix": "",
"loadingRecords": "Загрузка записей...",
"zeroRecords": "Записи отсутствуют.",
"emptyTable": "В таблице отсутствуют данные",
"paginate": {
"first": "Первая",
"previous": "<",
"next": ">",
"last": "Последняя"
},
"aria": {
"sortAscending": ": активировать для сортировки столбца по возрастанию",
"sortDescending": ": активировать для сортировки столбца по убыванию"
}
},
"iDisplayLength": 10,
"aLengthMenu": [[ 3, 10, 20, 50, 100 ,-1],[ 3, 10,20,50,100,"все"]],
stateSave: true,
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$(nRow).attr('id', aData[0]);
},
'serverSide': 'true',
'processing': 'true',
'paging': 'true',
'order': [],
'ajax': {
'url': 'fetch_data.php',
'type': 'post',
'data': {
from_attr_1_l: from_attr_1_l,
from_attr_2_l: from_attr_2_l
},
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
} }); });
`
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-md-8">
<table id="example" class="table">
<thead>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
I used different solutions also from https://datatables.net/examples/api/multi_filter_select.html and https://datatables.net/forums/discussion/73081/select-dropdown-list-filter but didn't work.
My target is to have an individual filtering for column. My reference is: https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html
The problem I am encountering right now when I type, my datatable doesn't do any filtering and it shows an error regarding CURSORPOSITION:
I followed the guide thoroughly and made a lots of research but I still failed to achieve my goal. I hope you can help me
Views:
<table id="example" class="table table-bordered table-hover table-striped is-narrow is-hoverable is-fullwidth text-nowrap" style="width: 100%;">
<thead>
<tr>
<th>TESTING ID</th>
<th>TESTING ACTION</th>
<th>TESTING DESC</th>
<th>TESTING Date</th>
<th>TESTING VENUE</th>
<th>TESTING TICKET</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
$(document).ready(function() {
$('#example thead tr')
.clone(true)
.addClass('filters')
.appendTo('#example thead');
table = $('#example').DataTable({
dom: 'lfrtip',
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$(
'input',
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
});
},
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/lists')?>",
"type": "POST",
async:true,
dataType: "json",
"data": function(data){
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
i have loaded the following jqGrid grid in regards to car annual check up for maintenance data.
On chrome this looks like this:
This was generated as a react object, the code as follows:
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/start/jquery-ui.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" />
</head>
<body>
<div id="divContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script type="text/babel" src="sample.jsx">
</script>
</body>
</html>
JSX code:
var SampleGrid = React.createClass({
componentDidMount:function(){
this.gridLoad();
},
gridLoad:function(){
var mydata = [
{ id: "1", test: "Engine checkup", teststart: "12/12/2016", testend: "12/30/2016", passed: true},
{ id: "2", test: "Electrical Checkup", teststart: "1/2/2017", testend: "1/3/2017", passed: false},
{ id: "3", test: "Chasis checkup", teststart: "1/4/2017", testend: "1/5/2017", passed: false},
{ id: "4", test: "Aerodynamics checkup", teststart: "1/6/2017", testend: "1/9/2017", passed: true},
{ id: "5", test: "Balance and stability checkup", teststart: "1/10/2017", testend: "1/12/2017", passed: true},
{ id: "6", test: "Report", teststart: "", testend: "", closed: false }
];
jQuery("#grid100").jqGrid({
colNames: ['test','passed','test started','test ended'],
colModel: [
{name: 'test', index: 'test', width: 220 },
{name: 'passed', index: 'passed', width: 60, align: 'center', formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'}, formatoptions: { disabled: false},
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' colspan="3"' }},
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
},
{name: 'teststart', index: 'teststart', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}},//return ' colspan="5"'
{name: 'testend', index: 'testend', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}}
],
rowNum: 10,
rowList: [5, 10, 20],
threeStateSort:true,
gridview: true,
rownumbers: false,
autoencode: true,
ignoreCase: true,
sortname: "id",
viewrecords: true,
sortorder: "desc",
shrinkToFit: false,
});
for(var i=0;i<=mydata.length;i++)
jQuery("#grid100").jqGrid('addRowData',i+1,mydata[i]);
jQuery("#grid100").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'passed', numberOfColumns: 3, titleText: 'Test Duration'}
]
});
},
render:function(){
return(<div id="gridContainer" ref="refContainer">
<form>
<table id="grid100"></table>
</form>
</div>
)
}
})
ReactDOM.render(<SampleGrid />, document.getElementById('divContainer'));
But this behaves funny. when i ran the code in chrome it works perfectly fine but when i ran this on IE (my version is 10) it gives the following error on console
SCRIPT1046: Multiple definitions of a property not allowed in strict mode
At the moment i cannot figure out why the same code produces results in one browser and not in another. But i know this error raised since i have added the formater to the column passed
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
How do i fix this issue?
The reason of the problem: the usage of multiple formatter property for the column passed (see formatter: 'checkbox', ..., formatter:function(cellvalue, options, rowObject) {...}). You should remove or comment the formatter: 'checkbox' from your code.
I'd recommend you additionally:
never fill the grid with data using addRowData in the loop. You should remove the lines for(var i=0;i<=mydata.length;i++) jQuery("#grid100").jqGrid('addRowData',i+1, mydata[i]); from your code. Additionally you should add data: mydata parameter and to remove unneeded sortorder: "desc" option.
to remove all index properties from colModel
remove unneeded options gridview: true, rownumbers: false, ignoreCase: true. All the values are already defaults in free jqGrid.
Code to print excel and pdf
I would like to hide a column from a datatable using tabletool.
var tableTools = new $.fn.DataTable.TableTools(table, {
'aButtons': [
{
'sExtends': 'xls',
'sButtonText': 'Excel',
'sFileName': 'Article.xls'
},
{
'sExtends': 'print',
},
{
'sExtends': 'pdf',
'sFileName': 'Article.pdf',
'bFooter': false
},
],
'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'
You need to add "columns" to show (skipping as not to show) as example below:
{extend: 'print',
titleAttr: 'Print the results',
title: '',
exportOptions: {
columns: ':visible',
stripHtml: false,
**columns: [1, 2, 5, 6, 8, 9, 10]**,
},
text: '<i class="fa fa-print fa-lg text-success"></i>',
message: 'REPORT NAME' ,
customize: function (win) {
$(win.document.body)
.css('font-size', '10pt')
.prepend(
'<img src="" style="position:absolute; top:0; left:0;" />'
);
$(win.document.body).find('table')
.addClass('compact')
.css('font-size', 'inherit');
}
}
I have multiple grids in a page which are shown based on a drop down selection. The first time when the page is loaded and I select another grid name in the drop down that grid's data reload event is not fired but subsequent events fire properly. Can someone let me know what is the problem with first time event not getting fired?
The flow of the execution is as follows
On the page load all the grids numbered 2 to 4 are initialized without any URL. And grid 1 is loaded with data and shown to the user.
Also on page load other grid divs are hidden.
When a user selects any other grid name in the drop down that grids div is shown and a reload event is fired to load data with URL.
HTML code
<select id="gridType" onchange="javascript:onChangeGridType();">
<option value="1" selected="selected">Grid 1</option>
<option value="2">Grid 2</option>
<option value="3">Grid 3</option>
<option value="4">Grid 4</option>
</select>
<div id="grid1Div">
<table id="grid1">
<tr>
<td />
</tr>
</table>
<div id="pager1"></div>
</div>
<div id="grid2Div">
<table id="grid2">
<tr>
<td />
</tr>
</table>
<div id="pager2"></div>
</div>
<div id="grid3Div">
<table id="grid3">
<tr>
<td />
</tr>
</table>
<div id="pager3"></div>
</div>
<div id="grid4Div">
<table id="grid4">
<tr>
<td />
</tr>
</table>
<div id="pager4"></div>
</div>
Grid 1 initialization code
$("#grid1").jqGrid({
url: grid1URL,
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager1',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 1',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid1").jqGrid('navGrid',"#pager1",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 2 initialization code
$("#grid2").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager2',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 2',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid2").jqGrid('navGrid',"#pager2",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 3 initialization code
$("#grid3").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager3',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 3',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid3").jqGrid('navGrid',"#pager3",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 4 initialization code
$("#grid4").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager4',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 4',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid4").jqGrid('navGrid',"#pager4",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
onChangeGridType function
function onChangeGridType(){
var type = $("#gridType").val();
if (type == 1){
reloadGrid1();
$("#grid1Div").show();
$("#grid2Div").hide();
$("#grid3Div").hide();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "visible");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 2){
reloadGrid2();
$("#grid1Div").hide();
$("#grid2Div").show();
$("#grid3Div").hide();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "visible");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 3){
reloadGrid3();
$("#grid1Div").hide();
$("#grid2Div").hide();
$("#grid3Div").show();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "visible");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 4) {
reloadGrid4();
$("#grid1Div").hide();
$("#grid2Div").hide();
$("#grid3Div").hide();
$("#grid4Div").show();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "visible");
}
}
'reload functions`
function reloadGrid1() {
$("#grid1").jqGrid('setGridParam',{datatype : 'json',url : grid1URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid2() {
$("#grid2").jqGrid('setGridParam',{datatype : 'json',url : grid2URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid3() {
$("#grid3").jqGrid('setGridParam',{datatype : 'json',url : grid3URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid4() {
$("#grid4").jqGrid('setGridParam',{datatype : 'json',url : grid4URL}).trigger('reloadGrid', [ {page : 1} ]);
}
For other grids I changed the grid URL value to empty and datatype as "local" that did the trick.