How to add Dropdown in JQUERY DataTable? - javascript

I want to add Drop down with in a Data Table. But it's not working.
Here I am adding the code I tried:
_dataTables.markAttendanceTable = $('#markAttendanceTable').DataTable(
{
dom: '<"pull-right"f>rt<"bottom"ip><"clear">',
ordering: false,
searching: false,
paging: true,
pageLength: 10,
fixedColumns: false,
data: GetAllMarkAttendance(eventId),
language: {
search: "_INPUT_",
searchPlaceholder: "Search"
},
columns: [
{ "data": "Login.Name", "defaultContent": "<i>-</i>" },
{"data":null ,
render: function (d, t, r) {
debugger;
var $select = $("<select></select>", {
//"id": //r[0]+"start",
"id": "Select",
"value": "Select"
});
$.each(attended, function(k,v){
var $option = $("<option></option>", {
"text": v,
"value": k
});
if(d === v){
$option.attr("selected", "selected")
}
$select.append($option);
});
return $select.prop("outerHTML");
}
},
],
columnDefs: [
{ className: "text-left", "targets": [0] },
{ className: "text-center", "targets": [] },
//{ width: "30%", "targets": [0] },
//{ width: "25%", "targets": [1] },
],
});
Please give me your suggestions.

Related

html datatable compact column width

I am trying to make a js datatable that has a column called 'Audio', which right now does not utilize space very well:
I'm trying to change it so that the Audio column is only as wide as its widest text element, basically so it has no blank space:
I've tried manually setting the max-width but it hasn't made any difference, and I've explored some datatables options but with no luck so far
https://jsfiddle.net/1mzqf23w/
$(document).ready(function() {
var data = JSON.parse('[{"itemId":1,"audio":"01 Hey DJ.flac","format":"flac","length":"00:03:27","audioFilepath":"C:\Users\marti\Documents\ous supreme team - (1986) rappin\Hey DJ.flac","trackNum":1,"album":"Rappin","year":1986,"artist":"Worlds Famous Supreme Team"}, {"itemId":2,"audio":"02 Wow Dude DJ.flac","format":"flac","length":"00:03:27","audioFilepath":"C:\Users\marti\Documents\ous supreme team - (1986) rappin\Hey DJ.flac","trackNum":1,"album":"Rappin","year":1986,"artist":"Worlds Famous Supreme Team"}]')
//setup table
var reorder = false;
var searched = false;
var origIndexes = [];
var origSeq = [];
var origNim = [];
let tableId = `#1_table`;
//create table
var table = $(tableId).DataTable({
"autoWidth": true,
"pageLength": 5000,
select: {
style: 'multi',
selector: 'td:nth-child(2)'
},
columns: [
{ "data": "sequence" },
{ "data": "#" },
{ "data": "selectAll" },
{ "data": "audio" },
{ "data": "length" },
{ "data": "audioFilepath" },
{ "data": "trackNum" },
{ "data": "album" },
{ "data": "year" },
{ "data": "artist" },
//{ "data": "imgSelection" },
],
columnDefs: [
{ //invisible sequence num
searchable: false,
orderable: false,
visible: false,
targets: 0,
},
{ //visible sequence num
searchable: false,
orderable: false,
targets: 1,
},
{//select all checkbox
"className": 'selectall-checkbox',
"className": "text-center",
searchable: false,
orderable: false,
targets: 2,
},
{//audio filename
targets: 3,
type: "natural"
},
/*
{//audio format
targets: 4,
type: "string"
},
*/
{ //audio file length
targets: 4,
type: "string"
},
/*
{ //video output format
targets: 6,
type: "string",
orderable: false
},
*/
{//audioFilepath
targets: 5,
visible: false,
},
{//trackNum
targets: 6,
visible: true,
orderable: true,
},
{//album
targets: 7,
visible: true,
orderable: true,
},
{//year
targets: 8,
visible: true,
orderable: true,
},
{//artist
targets: 9,
visible: true,
orderable: true,
},
/*
{ //image selection
targets: 7,
type: "string",
orderable: false,
className: 'text-left'
},
*/
],
"language": {
"emptyTable": "No files in this upload"
},
dom: 'rt',
rowReorder: {
dataSrc: 'sequence',
},
});
//add dataset to table
var count = 1;
data.forEach(function (i) {
table.row.add({
"sequence": i.itemId,
"#": `<div style='cursor: pointer;'><i class="fa fa-bars"></i> ${count}</div>`,
"selectAll": '<input type="checkbox">',
"audio": i.audio,
"length": i.length,
//"outputFormat": i.vidFormatSelection,
//"outputLocation": "temp output location",
"audioFilepath": i.audioFilepath,
"trackNum": i.trackNum,
"album": i.album,
"year": i.year,
"artist": i.artist,
//"imgSelection": i.imgSelection,
}).node().id = 'rowBrowseId' + i.sampleItemId;
count++;
});
//draw table
table.draw();
} );
If you are able to use css then try:
{//audio filename
targets: 3,
type: "natural",
className: 'track-name'
},
.track-name {
width: 0 !important;
white-space: nowrap;
}

Datatables Error where column is undefined

I'm trying to see what is going wrong here:
var TableName = $('#List').DataTable({
autoWidth: false,
pagingType: "full_numbers",
order: [[ 1, "desc" ]],
serverSide: true,
processing: false,
ajax: "datatables.cfc?method=getTable",
columns: arr,
columnDefs: arrDefs
});
Here is how arr and arrDefs are coming:
var arr=[];
var arrDefs = [];
datacolumns.split(",").forEach((element)=>{
arr.push({data:element.trim()})
arrDefs.push({className: "editable alignCenter"})
});
arrDefs.push({
width: "1em", className: "deleteCol", orderable: false
});
But I am getting an error:
TypeError: column is undefined jquery.dataTables.js:1722:5
jQuery 7
my JSON
[
{
"DT_RowData": {
"pkey": 1
},
"DT_RowId": 1,
"id": 1,
"delete": "<img class=\"deleteButton\" src=\"delete.png\" alt=\"delete1\" />",
"title": "Dewey defeats Truman"
},
{
"DT_RowData": {
"pkey": 2
},
"DT_RowId": 2,
"id": 2,
"delete": "<img class=\"deleteButton\" src=\"delete.png\" alt=\"delete2\" />",
"title": "Men walk on Moon"
}
]

column buttons missing from datatables column visibility

We have a datatable that looks like this. As you can see, when you click the column visibility button only a line is appearing:
var dataTableDefaults ={
columnDefs: [
{
"targets": -1,
"orderable": false,
"searchable": false
},
{
"targets": "noSearchOrSort",
"orderable": false,
"searchable": false
},
{
"targets": "noSort",
"orderable": false,
},
{
"targets": "noSearch",
"searchable": false
},
{
"targets": "invisible",
"visible": false
}
],
buttons: [
{
extend : 'colvis',
columns : ":visible"
}
],
order: [[0, 'asc']],
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
language: {
loadingRecords: 'Loading...',
emptyTable: 'No Data available'
},
pagingType: 'full_numbers',
processing: true
};
var cols = [
null,
null,
null,
{ "bVisible" : false }
];
jointDefaults = $.extend(true,{},dataTableDefaults);
jointDefaults.columns = cols
$('#table').DataTable(
$.extend(
jointDefaults,
{
bServerSide: true,
bProcessing: true,
sAjaxSource: 'ajax.php',
fnServerData: function(sSource, aoData, fnCallback) {
aoData.push(
{
name: 'gt',
value: 1
},
{
name: 'mode',
value: pageMode
},
);
$.ajax({
dataType: 'json',
type: 'GET',
url: sSource,
data: aoData,
success: function (response) {
fnCallback(response);
}
});
}
}
)
);
Why are the show/hide buttons on the column visibility not appearing?

Reset Count using Data Tables on draw

I am currently using Data Tables. I have two tables that Add and Remove data from one table to another. I have a count at the moment that is working somewhat, but when the table draws from one table to another the count is not being reset. It also seems to happen when moving pagination. Is there a way I can get JQuery to set a dynamic id.
Currently, this is what I have:
var selectedContractsTable = $('#catalogueLinkedContractsTable').DataTable({
sAjaxSource: linkedUrl,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: false,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No linked contracts found.",
zeroRecords: "No linked contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
// id number added for testing purposes
var removebuttonData = `<button class=\"btn btn-danger br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"RemoveContractBtn_` + count + `\">Remove</button>`;
count++;
return removebuttonData;
}
}
],
autoWidth: false
});
#* Setup the (Non-Selected) Contracts table (data, search, paging handled server side) *#
count = 0;
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
// id number added for testing purposes
var addbuttonData = `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn_` + count + `\">Add</button>`;
count++;
return addbuttonData;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
https://jsfiddle.net/vo5yfnd4/
Found that I could use meta.row
Which was in the documentation: https://datatables.net/reference/option/columns.render

How do I iterate thru a specific column in a DataTable?

I have a JSON file that looks like
[
{
"Title": "Something",
"FileName": "2014/mycollege/myvolume.pdf",
"Course": "01 - Dangerous Book for Boys",
"Year": "2014",
"Category": "Ethics",
"Group": "East Campus"
},
function getMyEdMaterials(result) {
$.getJSON("/materials/assets/json/materials.json", function(data) {
for (var key in data) {
datatableObject[data[key].Group] = datatableObject[data[key].Group] || [];
datatableObject[data[key].Group].push(data[key]);
datatableObject["all"] = datatableObject["all"] || [];
datatableObject["all"].push(data[key]);
}
for (var key in datatableObject) {
console.log(key.toLowerCase().replace(/\s/g, "-"));
console.log(datatableObject[key]);
var tableInstance = $('#' + key.toLowerCase().replace(/\s/g, "-") + '-table').DataTable({
bInfo: true,
bFilter: true,
columns: [{
title: "Title",
width: "30%",
render: function(data, type, row) {
return "" + row.Title + "";
}
},
{
title: "Course",
width: "30%",
data: "Course"
},
{
title: "Year",
width: "10%",
//data: "Year"
render: function(data, type, row) {
//year = year.push(row.Year);
return row.Year;
}
},
{
title: "Category",
width: "5%",
data: "Category"
},
{
title: "FileName",
width: "5%",
data: "FileName"
},
{
title: "Group",
width: "5%",
data: "Group"
}
],
columnDefs: [{
visible: false,
targets: [3, 4, 5]
}],
data: datatableObject[key],
deferRender: true,
dom: "<'toolbar'frltip >",
initComplete: function() {
this.api().columns(2).every(function() {
var column = this;
->>> having trouble getting the data from the column <<<---
if ((column == undefined) || (column == null)) {
console.log("data is null / undefined");
} else {
column.data().unique().sort().each(function(d, j) {
if ((d !== undefined) || (d !== null)) {
console.log(d + " is the year");
}
});
}
})
},
lengthMenu: [
[25, 50, 100, -1],
[25, 50, 100, "All"]
],
order: [
[2, 'desc'],
[3, 'asc'],
[1, 'asc'],
[0, 'asc']
],
orderMulti: true,
responsive: true,
});
}
})
};
What is the best way to get the data from the 3rd column from the DataTable?
Thanks
To get the data, just use
tableInstance.column(3).data()
or, if you want it in an array,
tableInstance.column(3).data().toArray()

Categories