DataTable - Getting error when putting select checkbox in first column - javascript

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.

Related

How to keep search working on modified render columns DataTables.js?

How do I keep the lookup working on the DataTables.js modified render column?
In the snippet below, I tried to search the data that is in the render columns does not show anything.
$('#release-table').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
ajax: "http://localhost/project/ajax/index_data.php?page=release",
order: [[ 0, 'desc' ]],
columns: [
{ data: 'no', name:'id', render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}},
{ "data": 0 },
{ "data": 1 },
{
"data": null,
"render": function(data, type, row, meta){
return '<img src="http://localhost/project/assets/dashboard/files/'+row["2"]+'" width="40" height="40">';
}, searchable: true, orderable: true
},
{
"data": null,
"render": function(data, type, row, meta){
return '<span><strong>'+row["4"]+'</strong></span> <br><strong class="text-muted">'+row["5"]+'</strong>';
}, searchable: true, orderable: true
},
{ "data": 6 },
{
"data": null,
"render": function(data, type, row, meta){
return '<i>UPC: '+row['7']+'</i> <br>ISRC: <i>'+row['8']+'</i>';
}, searchable: true, orderable: true
}
]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I remember having a similar issue and could not find a better solution than to add the search data in the column render inside an html element with display:none; in addition to what you are already rendering.
For example :
<span style="display:none;">${data.property_1} ${data.property_2}</span>
There might be a better solution to this, consider it more like a workaround, but it works.

How to get data values of checked rows of DataTables

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) {
}
}
]
});
})

Set default value before click event triggers

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();

How to seed data from AJAX response when Datatables is already initialized?

I have a mix of Select2JS and Datatables and here is the code involved in the issue:
$(function() {
var form_id = $('#form_id'),
form_results = $('#form_results');
form_results.DataTable();
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/forms/get/',
data: JSON.stringify({
form_id: null,
show_archived: !!$('#show_archived').is(':checked'),
get_first: false,
format: 'select2',
}),
cache: false,
success: function(data) {
form_id.removeAttr('disabled');
form_id.select2({
data: data,
closeOnSelect: true,
matcher,
sorter,
}).on('select2:select', function(e) {
var selected_element = $(e.currentTarget);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/manage_forms/getFormData/',
data: JSON.stringify({
form_id: selected_element.val(),
get_first: true,
}),
cache: false,
success: function(response) {
form_results.DataTable({
data: response.data,
retrieve: true,
stateSave: true,
responsive: true,
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
select: {
style: 'multiple',
selector: 'td:first-child',
},
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
On the PHP side there is a function building the data and send it back to the browser:
public function getFormData()
{
$inputJSON = file_get_contents('php://input');
$outputJSON = json_decode($inputJSON, true);
$arguments = array(
'Id' => $outputJSON['form_id'],
'FormName' => null,
'FormFileName' => null,
'FormTypeId' => 1
);
$form = $this->forms_model->get($arguments, $outputJSON['get_first'], self::$folders);
$result[] = array(
'',
'DT_RowId' => $form->Id,
$form->FormName,
$form->FaxNumber,
end(explode('/', $form->form_filepath))
);
return $this->output->set_content_type('application/json')->set_output(json_encode(array('data' => $result)));
}
The result from the above function looks like:
{
"data" : [
{
"0" : "",
"DT_RowId" : 3387,
"1" : "form",
"2" : "8772399284",
"3" : "form1.pdf"
}
]
}
For some reason the table is showing all the time "No data available in table" and I can't find where is the issue, can any find out what is wrong in my code?
I have spent the last two hours trying to figure this out but I can't.
Updates:
#charlietfl: the following didn't work at first complaining about the k not being defined so I modified a little bit however it didn't do the trick
response.data.map(function(k, o) {
return Object.keys(k).map(function(k) { return o[k];});
});
#CFP Support: your solution is not working either for some reason the table doesn't get updated with data.
In both cases I am not getting any Javascript error or nothing weird in the console it just does not work.
You need to add the "columns" and define them.
...stuff...
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
columns: [
{data: "0"},
{data: "DT_RowId"},
{data: "1"},
{data: "2"},
{data: "3"}
], ....etc...
This tells the table what column to match with the incoming data (so you will need a table with 5 columns in the HTML - or build it with JS {not sure what you are using, but if you need help...}
This should get you past the immediate issue though.
EDIT: JSFiddle - https://jsfiddle.net/CFPSupport/5utwh4v3/6/
EDIT2: I see the issue - you are initializing then wanting to put more data.... OK.....
You should get the data IN the datatable init, not init+AJAX.... https://datatables.net/reference/option/ajax

Send more values via URL

I am using Datatable plug-in to print values from database.
I get results and it prints in table. Now I am having trouble with sending values to the other file. Values that I need to send are userID, all titles of column except for last title, and two other variables which contains date.
When I click on '', beside data that contains userId, I need to send "User, Work time, Additions, Business, Break" as well as two variables printed below.
Other two variables are:
var date1 = "2017-01-01";
var date2 = "2017-02-28";
$('#myData').DataTable( {
data: dataSet,
fixedHeader: true,
responsive: true,
"columns": [
{ title: "User", data: "ime"},
{ title: "Work time", data: "Rad" },
{ title: "Additions", data: "Privatno" },
{ title: "Business", data: "Poslovno" },
{ title: "Break", data: "Pauza" },
{
"title": '<i class="icon-file-plus"></i>',
"data": "userID",
"render": function (data) {
return '' + '<i class="icon-file-plus"></i>' + '';
}, "width": "1%",
}
]
,"columnDefs": [ { "defaultContent": "-", "targets": "_all" },{ className: "dt-body-center", "targets": [ 5 ] } ]
});
Any help or advice is appreciated, I am stuck here.

Categories

Resources