Data table with headers and drop down both - javascript

I have a datatable, unfortunately, the table headers are replaced with drop down selects for each column.
When I try to print, it results in a bad output header for each column, since it concatenates all the values of a drop down.
How do I modify the code so, it prints the entire selected row(s) with a decent header name selected
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<table id="example" class="stripe compact row-border hover" width="100%"></table>
<script>
dataSet = [
["2019-02-05T08:25:08.816Z", "David", "Thorson", "AT&T", "david#gmail.com", "", "Message to be typed here", "Telephoned, Returned your call, Will call you, Quote Needed", "Paper", "Mike", "James, Mike", "", "\nMike - TESTED", "", "", ""],
["2019-02-06T15:00:56.923Z", "David", "Thorson", "AT&T", "david#gmail.com", "", "Message to be typed here", "Telephoned, Returned your call, Will call you, Quote Needed", "Paper", "Mike", "James, Mike", "", "\nMike - OK", "", "", ""],
["2019-02-06T19:39:19.476Z", "cd", "", "", "", "275-9288", "", "Quote Needed", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
["2019-02-06T20:15:31.693Z", "Jo", "blanc", "", "", "275-6855", "call about stone", "Please call, Quote Needed", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
["2019-02-06T23:47:47.663Z", "Dave", "bell", "", "", "285-8958", "", "Returned your call", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
];
const dataTable = $('#example').DataTable({
data: dataSet,
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
text: 'Print all',
exportOptions: {
modifier: {
selected: null
}
}
},
{
extend: 'print',
text: 'Print selected'
}
],
select: true,
ordering: false,
"pageLength": 100,
columns: [{
title: "Date"
}, {
title: "Fname"
}, {
title: "Lname"
}, {
title: "Company"
}, {
title: "Email"
}, {
title: "Phone"
}, {
title: "Message"
}, {
title: "Priority"
}, {
title: "Source"
}, {
title: "Assigned"
}, {
title: "By"
}, {
title: "Info"
}, {
title: "SMS"
}, {
title: "Completion"
}, {
title: "CRM Number"
}, {
title: "Notes"
}],
initComplete: function() {
const table = this.api();
table.columns().every(function() {
console.log($(this.header()).text())
const title = $(this.header()).text();
$(this.header()).html(`<select><option value="">${title} (All)</option></select>`);
const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
$(this.header()).find('select').append(options);
});
}
});
$('#example').on('change', 'thead select', event => dataTable.column($(event.target).closest('th')).search($(event.target).val()).draw());
</script>
</body>
</html>

Related

How to add an 'id' to json file at first line. [javascript][node.js]

I found a working script to add an id to each object;
function addId(id) {
return function iter(o) {
if ('fediverse' in o) {
o.id = id++;
}
Object.keys(o).forEach(function (k) {
Array.isArray(o[k]) && o[k].forEach(iter);
});
};
}
var data = [{"fediverse": "#username#mastodon.online", "name": "alternatenamehere", "alternate_names": "", "gender": "", "category": "", "description": "description here.", "link": "https://mastodon.online/users/username", "image": "https://files.mastodon.online/accounts/avatars/image.jpg", "language": "", "region": "", "user": true, "group": false, "creator": false, "companyOrganization": false, "project": false, "applicationSoftware": false}];
data.forEach(addId(1))
console.dir(data, {depth: null, colors: true, maxArrayLength: null});
This script outputs;
[
{
fediverse: '#username#mastodon.online',
name: 'alternatenamehere',
alternate_names: '',
gender: '',
category: '',
description: 'description here.',
link: 'https://mastodon.online/users/username',
image: 'https://files.mastodon.online/accounts/avatars/image.jpg',
language: '',
region: '',
user: true,
group: false,
creator: false,
companyOrganization: false,
project: false,
applicationSoftware: false,
id: 1
}
]
the problem is the search I use detects ids from the first line only. how can I add the id at the first line instead of the last line?

passing a button as a table column title in Vuejs

I want to make one of my table's column headers a clickable button. receives columns from parent like via an array like this. As you can see I want to pass a button as the last title.
<BaseTable
:columns="table.columns"
</BaseTable>
.
.
.
table: {
columns: [
{
title: "Role",
},
{
title: "No."
},
{
title: "Milestone"
},
{
title: "Status"
},
{
title: "Condition"
},
{
title:
'<button >+ View all</button>',
}
]
}
And then table component receives it as a prop an displays it like this:
<tr>
<th>
{{ column.title }}
</th>
</tr>
So the end product should look something like this:
How can I do this?
what about doing something like this?
<th>
<button v-if="column.isBtn">{{column.title}}</button>
<template v-else>{{column.title}}</template>
</th>
now in your columns array make the last object look like this:
{
title: "View all",
isBtn: true
}
so what I did is only add button to the table header column and only show it when I pass isBtn with value true in the column object
Hope this code can help you.
I recommend to use scoped slots in order to customize the rendering of that cell :
Vue.component('BaseTable', {
props: ['columns', 'data'],
template: `<table>
<thead>
<tr >
<th v-for="(col,i) in columns" :key="i">
<template v-if="col.key && $scopedSlots[col.key]" >
<slot :name="col.key" :column="col"></slot>
</template>
<template v-else>
{{col.title}}
</template>
</th>
</tr>
</thead>
</table>`
})
var app = new Vue({
el: '#app',
data: {
employees: [{
"id": "1",
"employee_name": "Tiger Nixon",
"employee_salary": "320800",
"employee_age": "61",
"profile_image": ""
},
{
"id": "2",
"employee_name": "Garrett Winters",
"employee_salary": "170750",
"employee_age": "63",
"profile_image": ""
},
{
"id": "3",
"employee_name": "Ashton Cox",
"employee_salary": "86000",
"employee_age": "66",
"profile_image": ""
},
{
"id": "4",
"employee_name": "Cedric Kelly",
"employee_salary": "433060",
"employee_age": "22",
"profile_image": ""
},
{
"id": "5",
"employee_name": "Airi Satou",
"employee_salary": "162700",
"employee_age": "33",
"profile_image": ""
},
{
"id": "6",
"employee_name": "Brielle Williamson",
"employee_salary": "372000",
"employee_age": "61",
"profile_image": ""
}
],
columns: [{
title: 'ID',
},
{
title: 'employee name',
},
{
title: 'employee salary',
},
{
title: 'employee age',
},
{
title: 'View All',
key: 'viewall'
},
]
},
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.x/dist/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<div id="app">
<base-table :columns="columns">
<template v-slot:viewall="{col}">
<button class="btn btn-primary">+View All</button>
</template>
</base-table>
</div>

tabulator is not a function

I am following quick start guide in tabulator(v4.2+) - http://tabulator.info/docs/4.2/quickstart which worked as expected, when I included a button click function inside my html script I get .tabulator is not a function error and the table variable seems to be printing undefined in the browser console,
When i try to print in the browser console it returns table object but not console.log from the code
var tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
col: "red",
dob: ""
}, {
id: 2,
name: "Mary May",
age: "1",
col: "blue",
dob: "14/05/1982"
}, {
id: 3,
name: "Christine Lobowski",
age: "42",
col: "green",
dob: "22/05/1982"
}, {
id: 4,
name: "Brendon Philips",
age: "125",
col: "orange",
dob: "01/08/1980"
}, {
id: 5,
name: "Margret Marmajuke",
age: "16",
col: "yellow",
dob: "31/01/1999"
}, ];
table = new Tabulator("#example-table", {
height: 200,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
}, {
title: "Age",
field: "age",
align: "left",
formatter: "progress"
}, {
title: "Favourite Color",
field: "col"
}, {
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}, ],
rowClick: function(e, row) {
alert("Row " + row.getData().id + " Clicked!!!!");
},
});
console.log(table);
$("#savebtn").click(function(e) {
e.preventDefault()
console.log(table)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
<div class="form-group">
<label for="comment2"></label>
<div id="example-table"></div>
</div>
<input type="submit" value="Save" id="savebtn" />
The error is coming in this part of the code when the button click happens, table object is printing as undefined ?
$("#savebtn").click(function(e) {
e.preventDefault()
console.log(table)
});
Use var keyword
var table = new Tabulator(
const tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
col: "red",
dob: ""
}, {
id: 2,
name: "Mary May",
age: "1",
col: "blue",
dob: "14/05/1982"
}, {
id: 3,
name: "Christine Lobowski",
age: "42",
col: "green",
dob: "22/05/1982"
}, {
id: 4,
name: "Brendon Philips",
age: "125",
col: "orange",
dob: "01/08/1980"
}, {
id: 5,
name: "Margret Marmajuke",
age: "16",
col: "yellow",
dob: "31/01/1999"
}, ];
const table = new Tabulator("#example-table", {
height: 200,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
}, {
title: "Age",
field: "age",
align: "left",
formatter: "progress"
}, {
title: "Favourite Color",
field: "col"
}, {
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}, ],
rowClick: function(e, row) {
alert("Row " + row.getData().id + " Clicked!!!!");
},
});
console.log(table.getData());
$("#savebtn").click(function(e) {
// e.preventDefault()
// console.log(table.getData());
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
</head>
<body>
<div class="form-group">
<label for="comment2"></label>
<div id="example-table"></div>
</div>
<input type="submit" value="Save" id="savebtn" />
</body>
</html>

Warning: Cannot reinitialise Datatable issue

Am using Jquery Datatable to render table.
By default the page wont display any table and there's a search box on the page, on entering a value it will make a call to database and render the datatable according to the response from database.
So now once the datatable is rendered, if I enter a new value in search box and call the datatable to be rendered it gives me above error.
I tried bdestroy and redrawing table but nothing seems to work for me.
$(document).ready(function() {
var resultArray = [
["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "2002", "XXX5", "XXX5", "XXX5", "", "1864", "2017", "VERSION", "23004746", "XXX5", "", "One Time", "", "", "", "", "", "", "21004482", "9189", "Feature Set", "20003880", "XXX5", "XXX5", "BASE", "19-APR-2017", "04-18-2017", "3877", "", ""],
["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "1865", "Deluxe", "EDITION", "", "", "", "", "", "", "", "", "", "", "", "9190", "Charge", "", "", "", "", "", "", "", "", ""]
];
console.log(JSON.stringify(resultArray));
var table = $('#example').DataTable({
columns: [{
title: 'Item Master Number',
name: 'ItemMasterNumber'
}, {
title: 'Description',
name: 'Description'
}, {
title: 'First Processing Date',
name: 'FirstProcessingDate'
}, {
title: 'Alias',
name: 'Alias'
}, {
title: 'Master Price',
name: 'MasterPrice'
}, {
title: 'Product Id',
name: 'ProductId'
}, {
title: 'Product Description',
name: 'ProductDescription'
}, {
title: 'Feature Set#',
name: 'FeatureSetId'
}, {
title: 'Feature Set Code',
name: 'FeatureSetCode'
}, {
title: 'Feature Set Name',
name: 'FeatureSetName'
}, {
title: 'Feature Set Description',
name: 'Feature Set Description'
}, {
title: 'Enablement Type',
name: 'Enablement Type'
}, {
title: 'Feature Id',
name: 'FeatureId'
}, {
title: 'Attribute Name',
name: 'AttributeName'
}, {
title: 'Attribute Value',
name: 'AttributeValue'
}],
data: resultArray,
rowsGroup: [
// Always the array (!) of the column-selectors in specified
// order to which rows groupping is applied.
// (column-selector could be any of specified in:
// https://datatables.net/reference/type/column-selector)
'ItemMasterNumber:name', 'Description:name', 'FirstProcessingDate:name', 'Alias:name', 'MasterPrice:name',
'ProductId:name',
'ProductDescription:name',
'FeatureSetId:name',
'FeatureSetCode:name'
],
pageLength: '20',
});
});
I am calling above code each time the value is entered in the search box and clicked on a button besides it.
All I want is to display the new data on the Datatable.
How can I resolve this error.
Here's a JSFiddle/snippet I threw together real quick, please let me know if this helps: https://jsfiddle.net/p9pot11h/5/
var dataTable_ = null;
var resultArray = [
["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "2002", "XXX5", "XXX5", "XXX5", "", "1864", "2017", "VERSION", "23004746", "XXX5", "", "One Time", "", "", "", "", "", "", "21004482", "9189", "Feature Set", "20003880", "XXX5", "XXX5", "BASE", "19-APR-2017", "04-18-2017", "3877", "", ""],
["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "1865", "Deluxe", "EDITION", "", "", "", "", "", "", "", "", "", "", "", "9190", "Charge", "", "", "", "", "", "", "", "", ""]
];
var resultArray2 = [
["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
];
$(document).ready(function() {
//console.log(JSON.stringify(resultArray));
dataTable_ = $('#example').DataTable({
columns: [{
title: 'Item Master Number',
name: 'ItemMasterNumber'
}, {
title: 'Description',
name: 'Description'
}, {
title: 'First Processing Date',
name: 'FirstProcessingDate'
}, {
title: 'Alias',
name: 'Alias'
}, {
title: 'Master Price',
name: 'MasterPrice'
}, {
title: 'Product Id',
name: 'ProductId'
}, {
title: 'Product Description',
name: 'ProductDescription'
}, {
title: 'Feature Set#',
name: 'FeatureSetId'
}, {
title: 'Feature Set Code',
name: 'FeatureSetCode'
}, {
title: 'Feature Set Name',
name: 'FeatureSetName'
}, {
title: 'Feature Set Description',
name: 'Feature Set Description'
}, {
title: 'Enablement Type',
name: 'Enablement Type'
}, {
title: 'Feature Id',
name: 'FeatureId'
}, {
title: 'Attribute Name',
name: 'AttributeName'
}, {
title: 'Attribute Value',
name: 'AttributeValue'
}],
data: resultArray,
rowsGroup: [
// Always the array (!) of the column-selectors in specified
// order to which rows groupping is applied.
// (column-selector could be any of specified in:
// https://datatables.net/reference/type/column-selector)
'ItemMasterNumber:name', 'Description:name', 'FirstProcessingDate:name', 'Alias:name', 'MasterPrice:name',
'ProductId:name',
'ProductDescription:name',
'FeatureSetId:name',
'FeatureSetCode:name'
],
pageLength: '20',
});
$('#search-button').on('click', function() {
var data = resultArray2;
var dataToSearch = $('#search').val();
if (dataToSearch == '') {
data = [];
}
// AJAX CALL TO GET RESULTS HERE
// SUCCESS FUNCTION TO CALL INSIDE AJAX SUCCESS
rePopulateTable(data);
});
});
var rePopulateTable = function(data) {
dataTable_.clear();
dataTable_.rows.add(data);
dataTable_.draw();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<body>
<input type="search" id="search" placeholder="Search" />
<input type="button" id="search-button" value="Search DB" />
<br/>
<br/>
<br/>
<table id="example">
</table>
</body>

datatable warning "unknown parameter 0"

I'm trying to use datatables with a set number of columns and an array of objects I get from jQuery ajax.
I get the error:
datatables warning (table id = myId requested unknown parameter 0 from the data source for row 0
Searching the internet has shown me that it's probable I have a different number of column headers and column data in my message_json array;
I have 21 columns set up in my data table initialization:
var construct_messages_table = function(message_json){
var oTable = $('#tableId').dataTable( {
"sPaginationType": "full_numbers",
"bProcessing": true,
"bDeferRender": true,
"aaData": message_json,
"aoColumns": [
{ "sTitle": "coloumn1"},
{ "sTitle": "coloumn2"},
{ "sTitle": "coloumn3"},
{ "sTitle": "coloumn4"},
{ "sTitle": "coloumn5"},
{ "sTitle": "coloumn6"},
{ "sTitle": "coloumn7"},
{ "sTitle": "coloumn8"},
{ "sTitle": "coloumn9"},
{ "sTitle": "coloumn10"},
{ "sTitle": "coloumn11"},
{ "sTitle": "coloumn12"},
{ "sTitle": "coloumn13"},
{ "sTitle": "coloumn14"},
{ "sTitle": "coloumn15"},
{ "sTitle": "coloumn16"},
{ "sTitle": "coloumn17"},
{ "sTitle": "coloumn18"},
{ "sTitle": "coloumn19"},
{ "sTitle": "coloumn20"},
{ "sTitle": "coloumn21"}
]
} );
};
And
for (var i = 1; i < message_json.length; i++){
console.log(Object.keys(message_json[i]).length);
}
shows all objects have a length of 21. What could be wrong here?
EDIT:
I've removed nulls as that might be the problem, but still no help.
for (var i = 0; i < message_json.length; i++){
for (var o in message_json[i]){
if (message_json[i][o] == null){
message_json[i][o] = "";
}
}
}
EDIT:
message_json is in this format
[
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"},
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"}];
But with lots more elements of course. And not just a duplicates.
Well the number of elements must be the same as the columns otherwise Datatables will look for a value not included in the data.
If you want to use a structure like the one in:
[
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"},
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"}];
It will be better to use "sAjaxSource" on your dataTable
When you add the aaData to your datatables normally they provide an array of arrays:
Example:
Fiddle
If your want to use a key:value JSON object you will need to add the mData property to your aoColumms config like this:
var oTable = $('#tableId').dataTable( {
"sPaginationType": "full_numbers",
"bProcessing": true,
"bDeferRender": true,
"aaData": message_json,
"aoColumns": [
{ "sTitle": "coloumn1","mData":"type"},
{ "sTitle": "coloumn2","mData":"id"},
{ "sTitle": "coloumn3","mData":"name"},
{ "sTitle": "coloumn4","mData":"description"},
{ "sTitle": "coloumn5","mData":"is_bool"},...
This will tell datatables where to find the value for that column.

Categories

Resources