Table on page is giving back errors, but works fine - javascript

Every time I reload the page I receive a pop-up window with error:
DataTables warning: table id=data-table - Requested unknown parameter
'apply_to_workdays' for row 0, column 5. For more information about
this error, please see http://datatables.net/tn/4
Assuming from the link data table is trying to get some value but it is unable to get it. The table shows up fine. I get no other errors, just those two on reload.
it shows error about apply_to_workdays but the column with it shows up perfectly, and everything works fine. I get no other errors in console/network tab.
my blade.php
<div class="table-responsive dt-responsive">
<table id="data-table" style="width: 100%;" class="display">
<thead>
<tr>
<th class="text-center">Unit</th>
<th></th>
<th>Competence Level</th>
<th style="padding-left: 0" class>Quantity</th>
<th style="padding-right: 0" class="text-right">Start -</th>
<th style="padding-left: 0" class="text-left">Finish</th>
<th style="width: 1px">Workdays</th>
<th style="width: 1px">Weekends</th>
<th style="width: 1px">Holidays</th>
<th class="text-center">Practice Type</th>
<th style="width: 10%">Action</th>
</tr>
</thead>
</table>
</div>
JS for it:
(function () {
const url = 'rotation-needs';
const positionUrl = url + '/position';
const buttonColumn = 9;
const definitionFieldValues = ['name', 'description', 'active', 'apply_to_workdays', 'apply_to_weekends', 'apply_to_holidays'];
const definition_id = 'schedule_need_definition_id';
const required = [true, false, true];
const columnDefs = [
{targets: [1, 2, 3, 4, 5, 6, 7, 8], orderable: false},
{orderable: false, className: 'reorder', targets: [buttonColumn]},
{
targets: buttonColumn,
render: function (data, type, row) {
return "<button type=\"edit-button\" data-toggle=\"modal\" data-target=\"#edit-position-Modal\"class=\"tabledit-edit-button btn btn-primary waves-effect waves-light\" style=\"float: none; margin-right: 1vw;\"><span class=\"icofont icofont-ui-edit\"></span></button>"
+ "<button type=\"button\" id=\" \" data-toggle=\"modal\" data-target=\"#remove-Modal\"class=\"tabledit-delete-button btn btn-danger waves-effect waves-light active\" style=\"float: none;\"><span class=\"icofont icofont-ui-delete\"></span></button>";
}
},
{
targets: 0,
"createdCell": function (td, data, rowData, row, col) {
$(td).css('background-color', data.color);
$(td).css('color', colors.getContrasting(data.color));
},
render: function (data, type, row) {
if (type === 'display') {
return '';
} else {
return data;
}
}
},
{
targets: [1], className: 'text-center',
render: function (data, type, row) {
var result = '';
if (row.competence_level_id_min.name !== null) {
result = result + 'min. ' + row.competence_level_id_min.name + ' <br>';
}
if (row.competence_level_id_max.name !== null) {
result = result + 'max. ' + row.competence_level_id_max.name;
}
return result;
},
"createdCell": function (td, data, rowData, row, col) {
$(td).css('background-color', rowData.organization_unit.color);
$(td).css('border-top', '1px solid #ddd');
$(td).css('color', colors.getContrasting(rowData.organization_unit.color));
}
},
{
targets: 2, className: 'text-center'
},
{
targets: 3, className: 'text-right',
render: function (data, type, row) {
return data.substring(0, 5);
}
},
{
targets: 4, className: 'text-left',
render: function (data, type, row) {
return data.substring(0, 5);
}
},
{
targets: 5, className: 'text-center',
render: function (data) {
if (data !== 0) {
return "<label class=\"badge badge-success\">✔</label>";
}
}
},
{
targets: 6, className: 'text-center',
render: function (data) {
if (data !== 0) {
return "<label class=\"badge badge-success\">✔</label>";
}
}
},
{
targets: 7, className: 'text-center',
render: function (data) {
if (data !== 0) {
return "<label class=\"badge badge-success\">✔</label>";
}
}
},
{
targets: 8, className: 'text-center',
render: function (data, type, row) {
var result = '';
if (row.practice_type_id === 1) {
/*result = result + row.practice_type_id.name + ' <br>'; - na szybko bo nie wiem czmeu nie pobiera name*/
result = 'On-call';
} else if (row.practice_type_id === 2) {
result = 'Rotation';
} else {
result = 'Not assigned';
}
return result;
}
},
]
;
const columns = [
{"data": "organization_unit"},
{"data": "competence_level_id_min"},
{"data": "quantity"},
{"data": 'time_start'},
{'data': 'time_finish'},
{'data': 'apply_to_workdays'},
{'data': 'apply_to_weekends'},
{'data': 'apply_to_holidays'},
{'data': 'practice_type_id'},
{'data': 'schedule_need_definition_position_id'}
];
create.setOnHashSuccess(hash.switchToNew);
create.createHashItemButton(definitionFieldValues, url, required);
update.updateHashMenuItem(definitionFieldValues, url + '/get');
update.confirmUpdateHashMenuItem(url + "/update", definition_id, definitionFieldValues, required);
remove.removeHashMenuItem();
remove.confirmRemoveHashMenuItem(url, hash.onRemove);
dataTable.rowGrouping(0);
dataTable.displayLength(100);
need.initializeSelects();
need.initializeCreate();
need.initializeTableCRUD(url + '/position');
need.generate();
update.setOnSuccess(function () {
sidebar.loadContent(undefined, function () {
sidebar.setActive(hash.getCurrent());
});
});
errorHandling.alertDismissButton();
});
}());

Solved my issue, in my columnDefs (target 5,6,7) I had if statements without else statements I changed from:
{
targets: 5, className: 'text-center',
render: function (data) {
if (data !== 0) {
return "<label class=\"badge badge-success\">✔</label>";
}
}
},
to:
{
targets: 5, className: 'text-center',
render: function (data) {
if (data !== 0) {
return "<label class=\"badge badge-success\">✔</label>";
} else {
return "<label class=\"badge badge-danger\">X</label>";
}
}
},

Related

addrow undefined and remove button doesn't work in datatables

Yesterday i post a question ask about my addrow button.Problem solved.
It run smoothly,but I have new problems.
Firstly, my delete button which I was used the remove()API is not working.
Secondly, everytime I reload the page, in the first row col5 will have the value : undefined
Once again, I appreciate every answer to this question.
var table = null;
var arrData = [];
var arrDataPG = [];
arrData.push({
STT: 1,
id: 1,
product_type: "",
condition1: "",
rebate: 0.0,
});
$(document).ready(function () {
InitTable();
});
function InitTable() {
if (table !== null && table !== undefined) {
table.destroy();
}
table = $('#tableh').DataTable({
data: arrData,
"columns": [
{ "width": "25px" },
{ "width": "300px" },
{ "width": "300px" },
{ "width": "120px" },
{ "width": "200px" },
{ "width": "25px" },
],
columnDefs: [
{
title: "STT",
targets: 0,
data: null,
render: function (data, type, row, meta) {
return (meta.row + meta.settings._iDisplayStart + 1);
},
},
{
title: "Loại sản phẩm*",
targets: 1,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="product_type' + data.id + '" type="text" onchange="ChangeProductType(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.product_type + '">' + data.product_type + '</textarea>';
}
},
{
title: "Điều kiện*",
targets: 2,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="condition1' + data.id + '" type="text" onchange="ChangeCondition1(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.condition1 + '">' + data.condition1 + '</textarea>';
}
},
{
title: "Rebate(%)*",
targets: 3,
data: null,
width: "70",
render: function (data, type, row, meta) {
return '<div><input id="rebate' + data.id + '" type="number" style="width: 70px;" onchange="ChangeRebate(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.rebate + '"></div>';
}
},
{
title: "Ghi chú",
targets: 4,
data: null,
width: "250",
render: function (data, type, row, meta) {
return '<textarea style="width:200px;" id="note' + data.id + '" type="text" onchange="ChangeNote(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.note + '">' + data.note + '</textarea>';
}
},
{
title: "",
targets: 5,
data: null,
className: "dt-center",
width: "70",
render: function (data, type, row, meta) {
return '<div class="btn btn-danger removePG" style="cursor: pointer;font-size:25px;" onclick=removePG(\'' + data.id + '\')><i class="fa-solid fa-trash"></i></div>'
}
},
],
});
table.columns.adjust().draw();
}
$('#addRow').on('click', function () {
console.log(arrData.length);
if (arrData != '') {
var ida = arrData[0].id;
} else {
var ida = 1;
}
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].id > ida) {
ida = arrData[i].id;
}
};
arrData.push({
STT: ida + 1,
id: ida + 1,
product_type: "",
condition1: "",
rebate: 0.0,
note: ""
});
if (table != null) {
table.clear();
table.rows.add(arrData).draw();
}
});
$('#tableh').on('click','.removePG', function () {
var tableq = $('#table_h').DataTable();
tableq
.row($(this).parents('tr'))
.remove()
.draw();
});
function removePG(idc) {
let id = parseInt(idc);
if (arrData !== undefined) {
var find = arrData.find(function (item) {
return item.id === id;
});
if (find !== undefined) {
arrData = arrData.filter(function (item, index) {
return item.id !== id;
});
};
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="tableh" class="cell-border hover" style="width:100%"></table>
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script src="https://kit.fontawesome.com/60bf89e922.js" crossorigin="anonymous"></script>

How to get value textbox in datatable column jquery and push to a variable?

I want to get a value of 53.54.57 but somehow I always get the value of 53.53.53 not as expected. anyone can help me?
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{ data: 'harga' },
{ data: 'qty' },
{ data: 'total' },
{ data: 'remove' },
{ data: 'untung' },
]
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
$("#" + $(data.remove).attr("id")).val();
I use this function to retrieve data from the datatable, but the line can only be the same value. always a value of 53, how to get the value of a line in the column called 'remove'
Is my looping wrong? or is there another way to get that value?
Like #charlietfl said, it seems you're duplicating the element ids.
If I understood you correctly, and the id of your input(type number) is the value, then you only need to change one line:
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
//change this line
//master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
//for this one
master_barang_id = $("#" + data.remove).val();
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
This is a working example:
var jsonData = [{ "linenum": 1, "nama": "lampu economat 3w LED", "harga": 20000, "qty": 1, "total": 20000, "remove": 53, "untung": "X" }, { "linenum": 2, "nama": "lampu economat 5w LED", "harga": 25000, "qty": 1, "total": 25000, "remove": 54, "untung": "X" }, { "linenum": 3, "nama": "lampu economat 9w LED", "harga": 30000, "qty": 1, "total": 30000, "remove": 57, "untung": "X" }];
$("#btnGetData").click(function() {
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id = $("#" + data.remove).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
});
var oTable = $('#table-main').DataTable({
data: jsonData,
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{
data: 'harga',
"render": function (data, type, row, meta) {
return '<input type="text" value=' + data + ' />';
}
},
{
data: 'qty',
"render": function (data, type, row, meta) {
return '<input type="number" value=' + data + ' />';
}
},
{ data: 'total' },
{
data: 'remove',
"render": function (data, type, row, meta) {
return '<input type="number" id="' + data + '" value=' + data + ' />';
}
},
{ data: 'untung' },
]
});
input {
text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<div class="data-table-container">
<table id="table-main" class="table cell-border order-column stripe">
<thead>
<tr>
<th>linenum</th>
<th>nama</th>
<th>harga</th>
<th>qty</th>
<th>total</th>
<th>remove</th>
<th>untung</th>
</tr>
</thead>
</table>
</div>
<br>
<input type="button" id="btnGetData" value="GET DATA" />

Datatables JQuery Adding new row - not working

HTML :
<div class="datatable-header">
<button type="button" name="add" id="add" class="float-right btn btn-info">Add</button>
</div>
<div class="table-responsive">
<table class="table datatable-basic table-striped table-hover table-bordered"
data-data-url="<?= $this->url('bla/blabla/ajax', ['action' => 'list']) ?>
id="text-dataTable"
>
<thead>
<tr>
<th>Text</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
JQuery:
const textTable = $('#text-dataTable');
const textDataTable = textTable.DataTable({
"lengthMenu": [[10, 25, 50, 75, -1], [10, 25, 50, 75, "All"]],
"dom": '<"top"fBr><"datatable-scroll-wrap"t><"bottom mt-2"ilp>',
"lengthChange": true,
"pageLength": 25,
"autoWidth": false,
"searching": false,
"order": [[0, 'asc']],
"ajax": {
"url": textTable.data('data-url'),
"type": "POST"
},
"columnDefs": [
{ targets: [1], className: "text-center"},
],
"columns": [
{ data: "text", "render": function (data, type, full, meta) {
return '<textarea style="width: 100%" contenteditable id="text" class="update" data-id="'+full.id+'" data-column="text">' + data + '</textarea>';
}
},
{ data: "textId", "render": function (data, type, full, meta) {
let $html = '<a class="btn bg-success m-1 update" data-id="'+data+'"><i class="icon-floppy-disk"></i> Update</a>';
$html += '<a class="btn bg-danger m-1 remove" data-id="'+data+'"><i class="icon-trash"></i> Delete</a>';
$html += '<a class="btn bg-grey m-1 reset" data-id="'+data+'"><i class="icon-reset"></i> Reset</a>';
return $html;
}
},
],
"rowCallback": function (row, data, index) {
if (data.hasOwnProperty('rowClass')) {
$(row).attr('class', data.rowClass);
}
$('td:last', row).attr('class', 'text-center');
}
});
$('#add').click(function(){
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
}
);
textDataTable.draw( false );
const addedRowNode = addedRow.node();
$(addedRowNode).addClass('highlight');
});
Result:
it's updating the text for the first column and the data-id of the second column, my goal is to add a new empty row, which means i want the first column to have 'aa' and the second column to have 'bb' instead of the buttons. I tried hundreds of things in vain.
See Screenshot:
Second Thing I tried: which is a problem because if the user adds multiple rows at the same time and click insert one by one, it will always insert the value of the first new row added, since it's getting the value by id. And all the new rows have the same ID.
$('#add').click(function(){
let html = '<tr>';
html += '<td><textarea contenteditable id="new-row-text">aa</textarea></td>';
html += '<td><a class="btn bg-grey m-1 insert"><i class="icon-plus22"></i> Insert</a></td>';
html += '</tr>';
$('#text-dataTable tbody').prepend(html);
});
textDataTable.on('click', 'a.insert', function(){
swal.fire({
title: 'Are You Sure?',
showCancelButton: true,
confirmButtonClass: "btn-success",
reverseButtons: true,
showLoaderOnConfirm: true,
preConfirm: function (data) {
return new Promise(function (resolve, reject) {
$.post(
textDataTable.data('insert-url'),
{
text: $('#new-row-text').val()
},
(function data($data) {
resolve()
}),
'json'
).fail((function(xhr, status, error) {
swal.fire('Error', xhr.responseJSON.error, 'error');
}));
})
}
}).then(result => {
if (result.value) {
textDataTable.ajax.reload();
} else {
}
}, (function () {
}));
});
Solution:
const addedRow = textDataTable.row.add(
{
"text": "aa",
"textId": "bb",
"newRow": true
}
);
Then in the render function test to see if the newRow flag exists:
{ data: "textId", "render": function (data, type, full, meta) {
// Return data if new row
if (full.hasOwnProperty('newRow') {
return data;
}
.
.
},
Credit User 2Fkthorngren: https://datatables.net/forums/discussion/61522/problem-with-adding-new-empty-row/p1?new=1

Function to get row data works only in responsive mode in Datatables

When I click on the image in Reponsive mode, it will return the row data in console. But in normal view I get Undefined error.
var table = $('.dataTable').DataTable({
"responsive": true,
"columnDefs": [{
"targets": 4,
"data": null,
"render": function (data, type, full, meta) {
if (type === 'display') {
data = "<a href='#' width='30px' class='editMe' data='" + full[0] + "'><img src='/images/edit.png' width='30px' /></a>";
}
return data;
}
} ,
{
"targets": 0,
"visible": false,
"searchable": false
}]
});
$('.dataTable').on('click', '.editMe', function () {
console.log(table.row(this).data());
});
Use the code below instead:
$('.dataTable').on('click', '.editMe', function () {
var $row = $(this).closest('tr');
if($row.hasClass('child')){ $row = $row.prev(); }
console.log(table.row($row).data());
});
See this example for code and demonstration.

jQuery datatable - unexpected vertical scrollbar

I am trying display data in jQuery datatable but, I am seeing unexpected vertical scrollbar.
Fiddler: https://jsfiddle.net/8f63kmeo/15/
HTML:
<table id="CustomFilterOnTop" class="table table-bordered table-condensed" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
//variables
this.result = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ title: "<input name='SelectOrDeselect' value='1' id='ChkBoxSelectAllOrDeselect' type='checkbox'/>" },
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
scrollCollapse: true,
"scrollX": true,
scrollY: "50vh",
deferRender: true,
scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">i<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox text-center',
targets: 0,
render: function (data, type, row) {
return '';
}
}],
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row selected'
}
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 2; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
instance.result = instance.GetData(limit);
instance.customFilterOnTopGrid.rows.add(instance.result.RecordList);
instance.customFilterOnTopGrid.draw();
};
Report4Component.prototype.GetData = function (limit) {
//structure of the response from controller method
var resultObj = {};
resultObj.Total = 0;
resultObj.RecordList = [];
for (var i = 1; i <= limit; i++) {
resultObj.Total += i;
var record = {};
record.Description = "Some test data will be displayed here.This is a test description of record " + i;
record.Status = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)] + 'name text ' + i;
record.Count = i;
resultObj.RecordList.push(record);
}
return resultObj;
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
ISSUE:
I am wondering why the vertical scrollbar is appearing and why I am seeing an incorrect count...? Is it because my datatable has rows with multiple lines? As I have already set the scrolly to 50vh, I am expecting all the rows to be displayed.
Note:
The table should support large data too. I have enabled scroller for that purpose as it is required as per the application design. To verify that click on "Load all" button.
Any suggestion / help will be greatly appreciated?
You just need to remove property " scroller: true" it will solve your problem.
For demo please check https://jsfiddle.net/dipakthoke07/8f63kmeo/20/

Categories