I want to get the selected checkbox value from the data table, in my table, I have two columns and the first one is for the checkbox and the second one is for display values.
Here is just returning a checkbox. How can we know that there is a click that happens?
Help me.
Here is the code
function BindColumSelectTable(DataExchangeList) {
debugger
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'check', render: function (data, type, row) {
debugger;
return '<input type="checkbox"/>'
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});}
I'm using jquery data table
function BindColumSelectTable(DataExchangeList) {
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'check', render: function (data, type, row) {
var checkbox = $("<input/>",{
"type": "checkbox"
});
if(data === "1"){
checkbox.attr("checked", "checked");
checkbox.addClass("checked");
}else{
checkbox.addClass("unchecked");
}
return checkbox.prop("outerHTML")
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});}
Try this
Here is the answer I use onclick function for each click it will trigger the function
function BindColumSelectTable(DataExchangeList) {
debugger
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'ColumnCheck', render: function (data, type, row) {
debugger;
return '<input type="checkbox" onclick="ColumnCheck(this)"/>'
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});
}
the above code is the same i used in the question only one thing i added is an onclick function
and the onclick function is
function ColumnCheck(thisObj) {
debugger;
var dataExchangeCheckColumnVM = $('#columnSelectTable').DataTable().row($(thisObj).parents('tr')).data();
var dataExchangeCheckColumnList = $('#columnSelectTable').DataTable().rows().data();
for (var i = 0; i < dataExchangeCheckColumnList.length; i++) {
if (dataExchangeCheckColumnList[i].FieldCaption !== null) {
if (dataExchangeCheckColumnList[i].FieldCaption === dataExchangeCheckColumnVM.FieldCaption) {
dataExchangeCheckColumnList[i].ColumnCheck = thisObj.checked;
}
}
}
_dataExchangeColumnList = dataExchangeCheckColumnList;
}
so i used an property **ColumnCheck ** it is boolean variable. on each iteration it will added a true value if check box is checked
Related
I am using the SearchBuilder extension to filter data.
Because I am also using sever-side processing, I force a search only when the user presses the enter key, like example.
But when I click button ">" to add new criteria, the previous value is empty.
Any suggestion for me?
Here my code:
I use search:{true} to force search only search only user press enter
$table = $(`#${_options.table.id}`).DataTable({
dom: 'Blfrtip',
search: {
return: true
},
"processing": true, // for show progress bar
"serverSide": true,
"filter": true,
"pageLength": 2,
"pagingType": "full_numbers",
"ajax": {
"url": _options.table.urls.load,
"type": "POST",
"datatype": "json"
},
"ordering": true,
"order": [[2,'asc']],
//"order": [[0, 'asc'], [1, 'asc']]
"columns":[
{
"data": null,
"orderable": false,
"searchable": false,
"className": "text-center",
render: function (data, type, row, meta) {
let html = `<div class="icheck-primary input-group" style="display:block;">
<input type="checkbox" id="example1_${meta.row}">
<label for="example1_${meta.row}"></label>
</div>`;
return html;
},
searchBuilderType: 'html'
},
{
"data": "id",
"name": "Mã số",
"autoWidth": true,
"visible": false,
"searchable": false
},
{
"data": "title",
"name": "Tên danh mục",
"autoWidth": true,
searchBuilderType: 'string'
},
{
"data": "created",
"name": "Ngày tạo",
"autoWidth": true,
render: function (data, type, row, meta) {
return new Date(data).toLocaleDateString("vi-VN");
}
},
{
"data": "modified",
"name": "Ngày chỉnh sữa",
"autoWidth": true,
render: function (data, type, row, meta) {
return new Date(data).toLocaleDateString("vi-VN");
}
},
{
"data": "active",
"name": "Hoạt động",
"autoWidth": true,
"className": "text-center",
"width": "10%",
render: function (data, type, row, meta) {
let html = `<div class="icheck-primary input-group" style="display:block;">
<input disabled type="checkbox" ${data ? 'checked' : ''} id="example1_active_${meta.row}" name="terms">
<label for="example1_active_${meta.row}"></label>
</div>`;
return html;
}
},
{
"orderable": false,
"width": "15%",
"className": "text-center",
"data": null,
"render": function (data, type, row, meta) {
return `<a class="btn btn-info btn-sm" onclick="Edit('${row.id}', '${row.title}');" href="#">Edit</a> <a href="#" class="btn btn-danger btn-sm" onclick="Delete('${row.id}', '${row.title}');" >Delete</a>`;
}
}
],
"createdRow": function (row, data, dataIndex) {
let checkbox = $(row).children('td').first().find('input[type="checkbox"]');
let headerCheckbox = $($table.column().header()).find('input[type=checkbox]');
headerCheckbox.prop('checked', false);
checkbox.on('change', { rowIndex: dataIndex }, function (e) {
let checked = $(this).prop('checked');
let headerCheckbox = $($table.column().header()).find('input[type=checkbox]');
let tableId = $table.table().node().id;
let deletebutton = $(`button[aria-controls = ${tableId}][name=delete]`);
let rowIdx = e.data.rowIndex;
if (checked) {
$table.rows(rowIdx).select();
$count++;
if ($count == $table.rows().count()) {
headerCheckbox.prop('checked', true);
}
deletebutton.attr('disabled', false);
}
else {
$table.rows(rowIdx).deselect();
$count--;
if ($count == 0) {
deletebutton.attr('disabled', true);
}
headerCheckbox.prop('checked', false);
}
});
},
"initComplete": function (settings, json) {
// Add custom button into table wrapper
$table.buttons().container().appendTo(`#${_options.table.id}_wrapper .col-md-6:eq(0)`);
//Select all bycheckbox header
let headerCheckbox = $($table.column().header()).find('input[type=checkbox]');
headerCheckbox.on('change', { settings: settings }, function (e) {
let checked = $(this).prop('checked');
for (let i = 0; i < $table.rows().count(); i++) {
$($table.rows(i).column().nodes()[i]).find('input[type="checkbox"]').prop('checked', checked);
}
let deletebutton = $(`button[aria-controls = ${_options.table.id}][name=delete]`).attr('disabled', !checked);
(checked) ? $table.rows().select() : $table.rows().deselect();
});
},
"responsive": true,
"lengthChange": false,
"autoWidth": false,
language: {
searchBuilder: {
button: {
0: 'Criteria',
1: 'Criteria (one selected)',
_: 'Criteria (%d)'
}
}
},
"buttons": [
{
text: `<i class="fas fa-plus"> New</i>`,
className: 'btn btn-primary form-group',
attr: {
'name': 'new',
'style': 'background: #007bff !important; border-color: #007bff !important'
},
action: function (e, dt, node, config) {
ajaxFormAction(_options.modal.selector, _options.modal.id, 'Create new category', '/Admin/Category/Create', true, function (e) {
$table.draw();
});
}
},
{
text: `<i class="fas fa-trash"> Delete</i>`,
className: 'btn btn-danger form-group',
attr: {
'name': 'delete',
"disabled": true
},
action: function (e, dt, node, config) {
let ids = [];
let rows = $table.rows({ selected: true }).every(function (rowIdx, tableLoop, rowLoop) {
ids.push(this.data().id);
});
ids = ids.join(',');
ajaxDelete(ids, null, _options.table.urls.delete, function (e) {
$table.draw();
});
}
},
{
text: 'Filter',
className: 'btn btn-default form-group',
extend: 'searchBuilder'
}
]
})
$('<input id="example1_column" type="text" class="form-control form-control-sm" placeholder="aaaa" />').insertBefore($("#example1_filter input"));
return $table
I'm trying to enable some operations on my grid such as grouping, filtering and sorting, individually they works as shown in the docs but there is no an example of those functionality working together.
By myself I was able to combine sorting and filtering but grouping does not work when i'm adding it as it shown in the docs. look at at my code
<template>
<div>
<Grid :style="{height: '100%'}"
ref="grid"
:data-items="getData"
:resizable="true"
:reorderable="true"
#columnreorder="columnReorder"
:filterable="true"
:filter="filter"
#filterchange="filterChange"
:sortable="true"
:sort= "sort"
#sortchange="sortChangeHandler"
:groupable="true"
:group= "group"
#dataStateChange="dataStateChange"
:columns="columns">
</Grid>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
editID: null,
columns: [
{ field: 'AbsenceEmployeID', filterable:false, editable: false, title: '#'},
{ field: 'Employe', title: 'Employer', cell: DropDownEmployes},
{ field: 'Remarque', title: 'Remarque'},
{ field: 'Type', title: 'Type', cell: DropDownTypes},
{ field: 'CreatedDate', filter:'date', editable: false, editor: 'date', title: 'créé le', format: '{0:d}'},
{ title: 'Actions', filterable:false, cell: CommandCell}
],
filter: {
logic: "and",
filters: []
},
sort: [
{ field: 'CreatedDate', dir: 'desc' }
],
group: [],
gridData: []
}
}
mounted() {
this.loadItems()
},
computed: {
absencesList() {
return this.items.map((item) => Object.assign({ inEdit: item.AbsenceEmployeID === this.editID}, item));
},
getData() {
return orderBy(filterBy(this.absencesList, this.filter), this.sort);
},
...mapState({
absences: state => state.absences.absences
})
}
methods: {
loadItems () {
this.$store.dispatch('absences/getAbsences')
.then(resp => {
this.items = this.absences.map(item => item)
})
},
filterChange: function(ev) {
this.filter = ev.filter;
},
columnReorder: function(options) {
this.columns = options.columns;
},
sortChangeHandler: function(e) {
this.sort = e.sort;
},
// the following is for grouping but not yet used, read more
groupedData: function () {
this.gridData = process(this.getData, {group: this.group});
},
createAppState: function(dataState) {
this.group = dataState.group;
this.groupedData();
},
dataStateChange: function (event) {
this.createAppState(event.data);
},
}
}
</script>
The last three methods are not used yet, so filtering and sorting is working perfectly as of now. then in other to enable grouping I want to replace :data-items="getData" by :data-items="gridData" and run this.groupedData() method after the items are loaded but grouping doesn't work.
I think everything should be handle by the dataStateChange event and process() function but I also tried but without success
If you define the filterchange and sortchange events they are being triggered for filter and sort and you will have to updated data in their handlers. If you rather want to use datastatechage event for all the changes you have to remove the filterchange and sortchange events and the datastatechage event will be triggered instead of them. In this case you will have to update the data in its handler.
You can use the process method of #progress/kendo-data-query by passing the respective parameter each data change that is needed as in the example below:
const result = process(data, {
skip: 10,
take: 20,
group: [{
field: 'category.categoryName',
aggregates: [
{ aggregate: "sum", field: "unitPrice" },
{ aggregate: "sum", field: "unitsInStock" }
]
}],
sort: [{ field: 'productName', dir: 'desc' }],
filter: {
logic: "or",
filters: [
{ field: "discontinued", operator: "eq", value: true },
{ field: "unitPrice", operator: "lt", value: 22 }
]
}
});
Hers is a sample stackblitz example where such example is working correctly - https://stackblitz.com/edit/3ssy1k?file=index.html
You need to implement the groupchange method to handle Grouping
I prefer to use process from #progress/kendo-data-query
The following is a complete example of this
<template>
<Grid :style="{height: height}"
:data-items="gridData"
:skip="skip"
:take="take"
:total="total"
:pageable="pageable"
:page-size="pageSize"
:filterable="true"
:filter="filter"
:groupable="true"
:group="group"
:sortable="true"
:sort="sort"
:columns="columns"
#sortchange="sortChangeHandler"
#pagechange="pageChangeHandler"
#filterchange="filterChangeHandler"
#groupchange="groupChangeHandler"
/>
</template>
<script>
import '#progress/kendo-theme-default/dist/all.css';
import { Grid } from '#progress/kendo-vue-grid';
import { process } from '#progress/kendo-data-query';
const sampleProducts = [
{
'ProductID': 1,
'ProductName': 'Chai',
'UnitPrice': 18,
'Discontinued': false,
},
{
'ProductID': 2,
'ProductName': 'Chang',
'UnitPrice': 19,
'Discontinued': false,
},
{
'ProductID': 3,
'ProductName': 'Aniseed Syrup',
'UnitPrice': 10,
'Discontinued': false,
},
{
'ProductID': 4,
'ProductName': "Chef Anton's Cajun Seasoning",
'UnitPrice': 22,
'Discontinued': false,
},
];
export default {
components: {
Grid,
},
data () {
return {
gridData: sampleProducts,
filter: {
logic: 'and',
filters: [],
},
skip: 0,
take: 10,
pageSize: 5,
pageable: {
buttonCount: 5,
info: true,
type: 'numeric',
pageSizes: true,
previousNext: true,
},
sort: [],
group: [],
columns: [
{ field: 'ProductID', filterable: false, title: 'Product ID', width: '130px' },
{ field: 'ProductName', title: 'Product Name' },
{ field: 'UnitPrice', filter: 'numeric', title: 'Unit Price' },
{ field: 'Discontinued', filter: 'boolean', title: 'Discontinued' },
],
};
},
computed: {
total () {
return this.gridData ? this.gridData.length : 0;
},
},
mounted () {
this.getData();
},
methods: {
getData: function () {
this.gridData = process(sampleProducts,
{
skip: this.skip,
take: this.take,
group: this.group,
sort: this.sort,
filter: this.filter,
});
},
// ------------------Sorting------------------
sortChangeHandler: function (event) {
this.sort = event.sort;
this.getData();
},
// ------------------Paging------------------
pageChangeHandler: function (event) {
this.skip = event.page.skip;
this.take = event.page.take;
this.getData();
},
// ------------------Filter------------------
filterChangeHandler: function (event) {
this.filter = event.filter;
this.getData();
},
// ------------------Grouping------------------
groupChangeHandler: function (event) {
this.group = event.group;
this.getData();
},
},
};
</script>
I am trying to load a datatable on click of a button outside the datatable.
below is my piece of code
$('#buttonToLoadDatatable').on('click', function() {
$.ajax({
type: "GET",
url:"../fhParser/fhParser/downloadAndParseResume/v1",
}).done(function (result) {
var table = $('#example').DataTable( {
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-
12 hidden-xs'l>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"oLanguage": {
"sSearch": '<span class="input-group-addon"><i
class="glyphicon glyphicon-search"></i></span>'
},
"bDestroy": true,
"data":result,
"iDisplayLength": 15,
/**this portion was because I have a collapsible rows**/
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data":"email" }
],
rowCallback: function (row, data) {},
filter: false,
info: false,
ordering: false,
processing: true,
retrieve: true,
"fnDrawCallback": function( oSettings ) {
runAllCharts()
}
// rowCallback: function (row, data) {}
} );
console.log( result );
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
When I print the value in the browser console, it comes correctly as
{"email": "triedandtest#gmail.com"}, but it does not display in the datatable
There is no error also in the console or at the backend
Can you replace your code to
$('#buttonToLoadDatatable').on('click', function() {
$.ajax({
type: "GET",
url:"../fhParser/fhParser/downloadAndParseResume/v1",
}).done(function (result) {
var table = $('#example').DataTable( {
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-
12 hidden-xs'l>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"oLanguage": {
"sSearch": '<span class="input-group-addon"><i
class="glyphicon glyphicon-search"></i></span>'
},
"bDestroy": true,
"data":result.data,
"iDisplayLength": 15,
/**this portion was because I have a collapsible rows**/
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data":"email" }
],
rowCallback: function (row, data) {},
filter: false,
info: false,
ordering: false,
processing: true,
retrieve: true,
"fnDrawCallback": function( oSettings ) {
runAllCharts()
}
// rowCallback: function (row, data) {}
} );
console.log( result );
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
and check if that works
FYI changed "data":result, to "data":result.data,
Using this as an example how do I control the format of the values in the cells?
for example, how would I format the Extn. column to read 5,407 or 54.07?
Name Position Office Extn. Start date Salary
Airi Satou Accountant Tokyo 5407 $2008/11/28 $162,700
I have been searching here and here but I can't quite work it out. can anyone advise?
I have tried something like this, but am having no success:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
],
"aoColumnDefs": [ {
"aTargets": [ 4 ],
"mRender": function (data, type, full) {
//var formmatedvalue=data.replace("TEST")
//return formmatedvalue;
return '$'+ data;
}
}]
} );
} );
Use the columns.render option.
Either with the built-in helper, to get a thousand seperator (5,407):
{
title: "Extn.",
render: $.fn.dataTable.render.number(',', '.', 0, '')
},
JSFiddle example
Or do it yourself with a custom function (54.07):
{
title: "Extn.", render: function (data, type, row) {
return data / 100;
}
},
JSFiddle example
I am getting this error Cannot read property 'oFeatures' of undefined datatables I am using bubble editing of datatable editor
<script type="text/javascript">
var editor;
$(document).ready(function(){
// use a global for the submit and return data rendering in the examples
editor = new $.fn.dataTable.Editor( {
ajax: 'http://52.77.155.163/web/index.php?r=ivision/productprices/datatable',
table: '#example',
fields: [ {
label: "Id:",
name: "id"
},
],
formOptions: {
inline: {
onBlur: 'submit'
}
}
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 0 ) {
editor.bubble( this );
}
});
var table=$('#example').DataTable( {
ajax: 'http://52.77.155.163/web/index.php?r=ivision/productprices/datatable',
dom: "Bfrtip",
scrollY: 300,
paging: false,
bSort: false,
columns: [
{ data: "id" },
{ data: "getcat(cat_id)" },
{ data: "getproduct(p_id)" },
{ data: "m_price" },
{ data: "c_price" },
{ data: "e_price" },
{
data: null,
defaultContent: 'Delete',
orderable: false
}],
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
} );
});
</script>
I am getting this error in console, Cannot read property 'oFeatures' of undefined . I am using bubble editing for datatables.net editor.
I also get this error.
It was the issue, Editor's table property is different DataTable Id.
After use same Id, it's fixed.