I have a DataTables with a checkbox column on the 1st column of the DataTables, I need to get the data value of checked row, so for example:
checkBox simsPid ICCID IMEI
-------- ------- ----- ----
1 98789 AABBCC
x 2 18729 A3B4C5
I need to get the data values of checked row (in my use case above, I need to get simsPid, ICCID, and IMEI)
I have tried codes below, I have got checked rows but I don't have an idea on how to get the value?
I need advice.
$('#sims').DataTable({
destroy: true,
responsive: true,
info: false,
autoWidth: false,
filter: true,
lengthChange: false,
paging: false,
searching: true,
order: [1, 'asc'],
ajax: {
url: '#Models.AppSettings.Path.Deployment' + '/SIM/List/',
dataSrc: ''
},
columns: [
{
'data': null,
'defaultContent': '',
'targets': 0,
'checkboxes': {
'selectRow': true
}
},
{ data: 'simsPid', visible: false },
{ data: 'iccid', className: 'text-left', width: '10%', responsivePriority: 1 },
{ data: 'imei', className: 'text-left', orderable: true, width: '10%', responsivePriority: 2 }
],
dom: '<"card-header border-bottom p-1"<"head-label"><"dt-action-buttons text-end"B>><"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
buttons: [
{
text: 'Set Status',
className: 'btn btn-outline-warning',
action: function(e, dt, node, config) {
var client_table = $('#sims').dataTable();
var rows = $(client_table.$('input[type="checkbox"]').map(function() {
return $(this).prop("checked") ? $(this).closest('tr') : null;
}));
// here I got the rows, but I don't know how to get the value of simsPid. iccid, and imei
$.each(rows, function(index, rowId) {
});
}
},
{
text: 'Discard',
className: 'btn btn-outline-secondary',
action: function(e, dt, node, config) {
}
}
]
});
})
Related
ref
e.g i need to pull the column from empid - mname
$(document).ready(function() {
$('#empList').DataTable({
'fnCreatedRow': function(nRow, aData, iDataIndex) {
$(nRow).attr('empid', aData[0]);
},
'serverSide': 'true',
'processing': 'true',
'paging': 'true',
'order': [],
'ajax': {
'url': 'fetch_emp.php',
'type': 'post',
},
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0,4]
},
]
});
});
I tried to change the target to "_all" string but still gets error
I have button groups. Once user clicks on the link, it filters value based on the content in the link. By default I added selected class. I want default value of link which contains selected class to be considered for filtering before click event triggers. It works fine when user clicks on c-btn-group but not considers default value when page loads. As of now it shows complete data without filtering when page loads.
<div class="c-btn-group">
<a class="c-btn selected">Large Cap</a>
<a class="c-btn">Small Cap</a>
<a class="c-btn">virginica</a>
</div>
JS
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
Try the below script. Here is demo
Separate out logic of dataTable filtering inside filter function. Get selected text by $('.c-btn-group .selected').text(); and call filter(initialSelectedText);
var myList2;
$.ajax({
url: "https://raw.githubusercontent.com/markwsac/jsonfile/main/jsondata.json",
type: "get",
dataType: 'text',
async: false,
success: function(response) {
if (!response) return;
response = response.slice(0, -1); // trim ";" at the end
window.myList2 = JSON.parse(response);
},
error: function(err) {
console.log(err);
}
});
var myList = window.myList2;
$(document).ready(function () {
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
const initialSelectedText = $('.c-btn-group .selected').text();
filter(initialSelectedText);
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
filter(searchTerm);
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
});
function filter(searchTerm){
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
});
table.draw();
$.fn.dataTable.ext.search.pop();
}
DataTable provides an Option for this. When you are initializing your table, just use the searchCols option which would load the table with the initial search provided. for Example:
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}],
searchCols: [
null,
null,
null,
{ "search": "Large Cap" },
null,
null,
null,
]
})
Here is the link for this option https://datatables.net/reference/option/searchCols
You can also use the libraries own search method rather than implementing it yourself, so instead of writing:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
just write:
table.column(3).search(searchTerm).draw();
Using Tabulator 4.4.3
When filtering the checkbox normally, everything works
If I set a filtered checkbox to true on a column, it works:
headerFilterEmptyCheck: function (value) {
return !value;
},
However, with using persistentFilter: true and I reload the page, that checkbox filter will only display true=true, never false or null when unchecked (just return 0 rows)
My Column Definition
{
title: "do it?",
field: "hasToDoIt",
responsive: 0,
formatter: "tickCross",
formatterParams: {
allowEmpty: true,
allowTruthy: false,
tickElement: "<i class='fa fa-check'></i>",
crossElement: ""
},
headerFilter: "tickCross",
headerFilterEmptyCheck: function (value) {
return !value; //only filter when the value is true
},
sorter: "string",
headerSortTristate: true,
width: 80,
align: 'center'
},
Table Definition
new Tabulator("#" + config.Key, {
index: "_id",
reactiveData: true,
persistenceMode: true,
persistenceID: "accountsummary",
persistentSort: true,
persistentFilter: true,
autoResize: true,
layout: "fitColumns",
responsiveLayout: true,
virtualDomBuffer: 100,
headerSortTristate: true, //enable tristate header sort for all columns
data: this.state.Data,
columns: this.state.Columns,
groupBy: "Geo",
groupToggleElement: "header",
groupStartOpen: true,
sortOrderReverse: true,
initialSort: [{ column: "Geo", dir: "asc" }, { column: "Account", dir: "asc" }],
rowClick: (e, row) => {
});
}
After selecting the checkbox, reloading the page, the checkbox should show the filtered results and unchecking the box show return to show all rows
This is because persistent filters functionality only persists filters set through the setFilter function, not header filters.
I would like to access the dropdown list for length display of the jQuery Datatable before the data is loaded in the table, i have a problem that whenever the user select the lenght of records to display in the table , the table resize and trigger window.resize() and i want to access the dropdown list after the table initialization but before the data is loaded, here is what i trying to do but it doesn't work.
let table = $('#data-table').DataTable();
$(document).on('preInit.dt', function (e, settings)
{
$('select[name=data-table_length]').click(function ()
{
console.log('dropdown selected');
window_resize = false;
});
});
table = $('#data-table').DataTable({
destroy: true,
serverSide: false,
autoWidth: false,
paging: true,
order: [[1, 'asc']],
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
ajax: {
url: '/Observer/GetActiveClientsByProfileId',
type: 'POST',
data: {
ProfileId: profileId
},
dataSrc: ''
},
columns: [
{
title: 'Zone',
data: 'LastKnownZone',
},
{
]
});
I know it has been addressed already, but I'm just not getting it to work. I'm using DataTable Editor with resposnive and serverside. I'm getting an error when I put the checkbox in the first column like:
js:
var table = $('#mytable').DataTable( {
dom: "rt",
ajax: {
url: "/source.php",
type: "POST",
data: function (d) {
}
},
serverSide: true,
processing: true,
select: {
style: 'os',
selector: 'td:first-child'
},
columns: [
{
data: null,
defaultContent: "",
className: "select-checkbox",
orderable: false,
targets: 0
},
{ data: "logo" },
{ data: "name" },
{ data: "product" }
]
} );
That's the Error message:
DataTables warning: table id=mytable - Unknown field: (index 0)
php:
Editor::inst( $db, 'table' )
->fields(
Field::inst( 'logo' ),
Field::inst( 'url' ),
Field::inst( 'name' ),
Field::inst( 'product' )
)
... wenn putting in the last column it works:
...
columns: [
{ data: "logo" },
{ data: "name" },
{ data: "product" },
{
data: null,
defaultContent: "",
className: "select-checkbox",
orderable: false,
targets: 0
}
]
...
How can I get the checkbox in the first column? (So column 0)
add this in code
$("#table").DataTable({
'columnDefs': [{
'targets': 0,
'bSortable': false,
'render': function (data, type, full, meta){
return '<input type="checkbox"> <label>Checkbox</label>';
}
}]
})
Here the answer from the author:
You have server-side processing enabled, and the default ordering is to order on the first column. When that happens, DataTables is telling the server to order on the client-side generated column and throws an error.
Use ``order: [[1, 'desc']]` to resolve that.