Related
I was working on a web application with JQuery datatables in it, and I have ran into some issues.
I am using the detailsTable.on('click', 'button.edit', function () { ... }) function to catch clicking events on buttons with a class "edit". It is working just fine, and I figured out, that i can get the row data with using detailsTable.row($(this).parents('tr')).data();. But it contains only the data I recived in the ajax call.
My idea is to change the html of the button I clicked on, but I can't find any solution, how to modify it. (I'd like to modify only in this row.)
Any ideas?
My html:
<table id="datatable" class="table table-bordered table-striped table-hover table-sm table-head-fixed">
<thead>
<tr>
<th>Value 1</th>
<th>Value 2</th>
<th>Actions</th>
</tr>
</thead>
</table>
My javascript:
$(function () {
var mytable = $("#datatable").DataTable({
"ajax": {"url": "", dataSrc: "data"},
"columns": [
{ "data": "val_2" },
{ "data": "val_1" }
],
"columnDefs": [
{
"targets": 2,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="edit btn btn-info btn-sm" data-subid="'+full['id']+'"><i class="fa fa-wrench"> Edit</i></button>';
},
},
}
});
$('#datatable tbody').off('click')on('click', 'button.edit', function () { // Delete token
var data = mytable.row($(this).parents('tr')).data();
// I'd like to change the button, (I need to change the title, the fa-icon and the class, so basicely the whole html) like the way i did with "columnDefs"
});
});
Instead of accessing the source data values using data(), you can access the node using node(). Also, because you want to change the clicked button, you can get the <td> node for the cell in which the button is placed, instead of getting the row:
var td = mytable.cell($(this).parents('td')).node();
This can then be manipulated using jQuery or JavaScript - for example:
$( td ).find( 'button' ).html('I was ckicked');
Demo:
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
},
{
"id": "567",
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "$433,060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"extn": "6224"
},
{
"id": "432",
"name": "Airi Satou",
"position": "Accountant",
"salary": "$162,700",
"start_date": "2008/11/28",
"office": "Tokyo",
"extn": "5407"
},
{
"id": "987",
"name": "Brielle Williamson",
"position": "Integration Specialist",
"salary": "$372,000",
"start_date": "2012/12/02",
"office": "New York",
"extn": "4804"
}
];
$(document).ready(function() {
var mytable = $('#datatable').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
],
"columnDefs": [
{
"targets": 2,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="edit btn btn-info btn-sm" data-subid="'+full['id']+'"><i class="fa fa-wrench"> Edit</i></button>';
},
},
]
} );
$('#datatable tbody').off('click').on('click', 'button.edit', function () { // Delete token
var td = mytable.cell($(this).parents('td')).node();
$( td ).find( 'button' ).html('I was ckicked');
});
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="datatable" class="display dataTable cell-border" style="width:100%">
</table>
</div>
</body>
</html>
I am using DataTable plugin for show rows in table. I want to show duplicate rows in same color.
How i can do this someone pls help me.
In the below example Black Winters we have duplicate row.
I want to show these type of duplicate rows in different colors.
Like I have duplicate data Black Winters and Orange i want to show these both duplicate rows in different color combination eg.: Black Winters color will be red and Orange color will be like blue.
$(document).ready(function() {
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
}
];
$("#table1").DataTable({
data: data,
columns: [{
data: 'name'
},
{
data: 'position'
},
{
data: 'salary'
},
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
You can make use of below code where you can prepare map of duplicate rows inside 'rowCallback' function and apply color to dupliate rows in applyDuplicateRowColor function once datatable draw get completed
I have used duplicateColor array to pick random color for same rows, you can edit it and add more colors. also using duplicateColorIndex to get next duplicate color for next duplicate data, please make sure you have enough color in the array otherwise it will show arrayindexoutofbound error.
$(document).ready(function() {
var duplicateColor = ['red', 'blue', 'yellow', 'green'];
var len = duplicateColor.length;
var duplicateColorIndex = 0;
var duplicateRowMap = {};
$.fn.applyDuplicateRowColor = function() {
$("#table1 tr").each(function(){
var name = $(this).find('td:eq(0)').text();
var value = duplicateRowMap[name];
if(value!='x') {
$(this).css('color', duplicateColor[value]);
}
});
//reset variables
duplicateColorIndex = 0;
duplicateRowMap = {};
};
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,200"
},
{
"name": "Oranges",
"position": "Project Engineer",
"salary": "$1,100"
},
{
"name": "Oranges",
"position": "Project Engineer",
"salary": "$1,000"
}
];
$("#table1").DataTable({
data: data,
columns: [{
data: 'name'
},
{
data: 'position'
},
{
data: 'salary'
},
],
"rowCallback": function( row, data ) {
var name = duplicateRowMap[data.name];
if(name) {
if(name == 'X') {
duplicateRowMap[data.name] = duplicateColorIndex;
duplicateColorIndex++;
if(duplicateColorIndex==len)
duplicateColorIndex = 0;
}
} else {
duplicateRowMap[data.name] = 'X';
}
},
"fnDrawCallback": function( oSettings ) {
$(this).applyDuplicateRowColor();
}
});
//console.log(duplicateRowMap);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
You can implement this using
Using .map() method of array, in map method you just need to append new key with color value based on condition if duplicate row is count is greater then 1 then color will be orange otherwise 'red'.
Now need to use createdRow() method for data table.
See below working code snippet
$(document).ready(function() {
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120"
}, {
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
}, {
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
}].map((o,i,arr)=>{
o.color = arr.filter(({name})=>name===o.name).length>1 ?'orange':'red';
return o;
});
$("#table1").DataTable({
data: data,
columns: [{
data: 'name'
}, {
data: 'position'
}, {
data: 'salary'
}],
"createdRow": function(row, data, dataIndex) {
$(row).css("background-color", data.color);
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
First you need to check which elements are duplicates and you need to manage it's status in other array. so in createdRow you can check for duplicate rows.
Check on below link.
https://jsfiddle.net/t2cn571z/
Try below solution.
$(document).ready(function() {
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120"
},
{
"name": "Orange",
"position": "Developer",
"salary": "$1,700"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Orange",
"position": "Developer",
"salary": "$1,700"
}
];
//find duplicates values
var array = [];
data.forEach(myFunction)
function myFunction(item, index) {
if( array.length == 0)
{
array.push({"name":item.name,"isduplicate" : 0})
}
else
{
if (array.filter(e => e.name === item.name).length == 0)
/* vendors contains the element we're looking for */
{
array.push({"name":item.name,"isduplicate" : 0})
}
else
{
array = array.filter((e) => e.name !== item.name);
array.push({"name":item.name,"isduplicate" : 1})
}
}
}
$("#table1").DataTable({
data: data,
"createdRow": function ( row, data, index ) {
var dataValue = array.find(x => x.name === data.name);
if ( dataValue.isduplicate == 1 ) {
if(dataValue.name == 'Black Winters')
$(row).css('color','red')
else if(dataValue.name == 'Orange')
$(row).css('color','blue')
}
},
columns: [{
data: 'name'
},
{
data: 'position'
},
{
data: 'salary'
},
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
A little bit messy but it does what you need mostly. For a unique color for each set of different data you would need to created a random color variable and put that on the row instead of a class like I did. This is not very extendable but if you know how many columns then this works fine.
Good luck.
$(document).ready(function() {
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
}
];
$("#table1").DataTable({
data: data,
columns: [{
data: 'name'
},
{
data: 'position'
},
{
data: 'salary'
},
]
});
});
$(document).ready(function() {
// Search the table for doubles.
function SearchForDoubles() {
var table = $("#table1 tbody tr");
var counter1 = 0;
var counter2 = 0;
var tr_currentName = "";
var tr_newName = "";
var tr_currentPosition = "";
var tr_newPosition = "";
var tr_currentSalary = "";
var tr_newSalary = "";
table.each(function() {
// set the current tr html data
tr_currentName = $(this).find("td:nth-child(1)").html();
tr_currentPosition = $(this).find("td:nth-child(2)").html();
tr_currentSalary = $(this).find("td:nth-child(3)").html();
table.each(function() {
tr_newName = $(this).find("td:nth-child(1)").html();
tr_newPosition = $(this).find("td:nth-child(2)").html();
tr_newSalary = $(this).find("td:nth-child(3)").html();
/*
console.log(counter1 +"!="+counter2);
console.log(tr_currentName +"=="+tr_newName);
console.log(tr_currentPosition +"=="+tr_newPosition);
console.log(tr_currentSalary +"=="+tr_newSalary);
*/
// check if there is a match
if (counter1 != counter2 &&
tr_currentName == tr_newName &&
tr_currentPosition == tr_newPosition &&
tr_currentSalary == tr_newSalary
) {
// highlight the row
$(this).addClass("doubleRecord");
}
counter2++;
});
counter2 = 0;
counter1++;
});
}
SearchForDoubles();
});
.doubleRecord {
color: orange;
font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
There is option createdRow on datatable. You may check condition inside that option and add desire CSS.
Update: createdRow with initComplete and some logic do this for dynamic data. I edit answer after comment.
$(document).ready(function() {
var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$1,120"
},
{
"name": "Shree",
"position": "System Architect",
"salary": "$3,120"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
},
{
"name": "Black Winters",
"position": "Project Engineer",
"salary": "$1,300"
}
];
var names = [];
var dupliacteName = [];
$("#table1").DataTable({
data: data,
"createdRow": function(row, data, index) {
let name = data.name;
if (names.indexOf(name) > -1) {
dupliacteName.push(name);
}
$(row).attr('data-val', name).css({
"color": "orange"
});
names.push(name);
},
"initComplete": function(settings, json) {
$.each(dupliacteName, function(index, name) {
$("[data-val='" + name + "']").css({
"color": "red"
});
});
},
columns: [{
data: 'name'
},
{
data: 'position'
},
{
data: 'salary'
},
]
});
});
<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.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>salary</th>
</tr>
</thead>
</table>
I have very simple example of DataTables jQuery plugin with a simple javascript source that is rendered before a basic Vue.js binding:
JavaScript:
var aDemoItems =[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"name": "Garrett Winters",
"position": "Director",
"salary": "$5,300",
"start_date": "2011/07/25",
"office": "Edinburgh",
"extn": "8422"
},
{
"name": "Vivou fou",
"position": "Lazy nephew",
"salary": "$7,300",
"start_date": "2010/04/22",
"office": "Edinburgh",
"extn": "8422"
}
]
$('#missionTable').DataTable({
data: aDemoItems,
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'salary' },
{ data: 'office' }
]
});
var app = new Vue({
el: '#app',
data: {
name: packageName,
path: packagePath,
data: missionsData
}
})
HTML:
<table id="missionTable" class="display" width="100%"></table>
It seams to work but search, sorting, nb item display and pagination are disabled if Is use vue.js in spite of no error appears in console
Do you know what is wrong and how use Datatable and vue.js at same time?
I am trying to develop the following functionality,
https://datatables.net/extensions/responsive/examples/display-types/modal.html
I followed the exact same steps but, I am not getting the icons to launch the modal dialog,
Here is the complete code,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Responsive</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var dataset = {
"data": [
{
"first_name": "Airi",
"last_name": "Satou",
"position": "Accountant",
"office": "Tokyo",
"start_date": "28th Nov 08",
"salary": "$162,700"
},
{
"first_name": "Angelica",
"last_name": "Ramos",
"position": "Chief Executive Officer (CEO)",
"office": "London",
"start_date": "9th Oct 09",
"salary": "$1,200,000"
},
{
"first_name": "Ashton",
"last_name": "Cox",
"position": "Junior Technical Author",
"office": "San Francisco",
"start_date": "12th Jan 09",
"salary": "$86,000"
},
{
"first_name": "Bradley",
"last_name": "Greer",
"position": "Software Engineer",
"office": "London",
"start_date": "13th Oct 12",
"salary": "$132,000"
},
{
"first_name": "Brenden",
"last_name": "Wagner",
"position": "Software Engineer",
"office": "San Francisco",
"start_date": "7th Jun 11",
"salary": "$206,850"
},
{
"first_name": "Brielle",
"last_name": "Williamson",
"position": "Integration Specialist",
"office": "New York",
"start_date": "2nd Dec 12",
"salary": "$372,000"
},
{
"first_name": "Bruno",
"last_name": "Nash",
"position": "Software Engineer",
"office": "London",
"start_date": "3rd May 11",
"salary": "$163,500"
},
{
"first_name": "Caesar",
"last_name": "Vance",
"position": "Pre-Sales Support",
"office": "New York",
"start_date": "12th Dec 11",
"salary": "$106,450"
},
{
"first_name": "Cara",
"last_name": "Stevens",
"position": "Sales Assistant",
"office": "New York",
"start_date": "6th Dec 11",
"salary": "$145,600"
},
{
"first_name": "Cedric",
"last_name": "Kelly",
"position": "Senior Javascript Developer",
"office": "Edinburgh",
"start_date": "29th Mar 12",
"salary": "$433,060"
}
]
}
$.each(dataset.data, function (i, item) {
item.age = Math.floor((Math.random() * 70) + 1);
item.extn = Math.floor((Math.random() * 1000) + 1);
})
$('#example').DataTable({
"paging": false,
"info": false,
"filter": false,
"paging": false,
retrieve: true,
"processing": true,
data: dataset.data,
columns: [{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "age" },
{ "data": "start_date" },
{ "data": "salary" },
{ "data": "extn" }],
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
alert(row.data.length)
return 'Details for ' + data[0] + ' ' + data[1];
}
}),
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table'
})
}
}
});
});
</script>
</head>
<body>
<table width="100%" class="table table-striped table-bordered nowrap" id="example" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
Output:
You can even copy and paste the entire code in an HTML file and run it to see the behavior.
I am not seeing any errors in the console. I tested with IE 11 and Chrome.
Any suggestions / directions are greatly appreciated.
Edit:
Snapshot from jsbin.com/hehewiz/edit?html,output. (link created by bazzells)
The icons are hidden on a wide screen due to the collapsed class being removed from the table. The collapsed class is toggling based on the window width currently.
Your code is working just fine, when the screen gets smaller and at least one columns becomes hidden, the (+) icon appears.
This is because this option is for responsive display of information.
I am interested in creating a function that creates DataTables dynamically with the Data parameter passed in the function.
Below is what I wrote so far, the DataTables can add rows dynamically, but not the column header - can use some help here (I've read the DT API, but didn't find much help there).
var table2 = $('#example2').DataTable({
"paging" : true,
"ordering" : true,
});
// header row
table2.columns().header(data["header"]).draw();
// create rows
for (var prop in data["staff"]) {
table2.row.add([
data["staff"][prop].name,
data["staff"][prop].position,
data["staff"][prop].office,
data["staff"][prop].age,
data["staff"][prop].Start_date,
data["staff"][prop].salary
]).draw();
}
The Data passed into the function:
var data = {
"header": [
"Name",
"Position",
"Office",
"Age",
"Start_date",
"Salary"
],
"staff": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"office": "Edinburgh",
"age": 61,
"Start_date": "2011/04/25",
"salary": "$320,800"
},
{
"name": "Garrett Winters",
"position": "Accountant",
"office": "Tokyo",
"age": 63,
"Start_date": "2011/07/25",
"salary": "$170,750"
},
{
"name": "Ashton Cox",
"position": "Junior Technical Author",
"office": "San Francisco",
"age": 66,
"Start_date": "2009/01/12",
"salary": "$86,000"
}
]
};