How to display table with 2 headers using DataTables plugin? - javascript

I want to display similar table like W3.
Code:
$('table_1').DataTable({
ajax:'ajax_table_1.php',
paging:false,
});
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_1">
<caption>Delivery slots:</caption>
<tr>
<td></td>
<th scope="col">Monday</th>
<th scope="col">Tuesday</th>
<th scope="col">Wednesday</th>
<th scope="col">Thursday</th>
<th scope="col">Friday</th>
</tr>
<tr>
<th scope="row">Morning</th>
<td>Closed</td>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
<td>Closed</td>
</tr>
<tr>
<th scope="row">Evening</th>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
<td>Closed</td>
<td>Closed</td>
</tr>
</table>
HTML shows my goal which I want to achieve.
How to set up my data array that it should look like to implemented table with 2 headers to fill all table data with ajax call?

You can simply render your columns in order to achieve that check here for the docs
a short snippet to show what you can do is:
"columnDefs": [
{
"createdCell": function (td, cellData, rowData, row, col) {
$(td).attr("scope", "row");
}
"targets": 0 //this is your column number, just change it if you need another column
}
]

Related

Making entire rows AND columns in an HTML table drag/droppable?

I have a basic HTML table, with jQuery's sortable enabled to sort the table rows. (Codepen for the table; code is below)
My ultimate goal, is to be able to allow the user to drag/drop both rows and/or columns if they'd like. I am aware of the connectWith option which can be passed to sortable, but it seems to make all individual td cells moveable - I only want this to apply to entire columns or entire rows (not the individual cells).
I've had a look at jQuery-ui's sortable API documentation, but I am having a difficult time figuring out how this works; I am unsure if the basic sortable class can handle a scenario like this, or if I will need to construct some outside javascript to make this happen.
If I need to use my own javascript, that's not an issue - the problem is, I don't even know where to start (would it be something handled by event listeners?). I am not looking for someone to solve the problem for me - but curious if anyone knows if this sort of thing is possible with the basic sortable class, and if not (if I will need to construct my own js to do this), can you point me in the right direction on where to start, as I really am unsure.
Table HTML:
<table class="mytable">
<caption>My Table</caption>
<tr>
<td id="corner"></td>
<th scope="col">Col I</th>
<th scope="col">Col .II</th>
<th scope="col">Col .III</th>
</tr>
<tr class="sortme">
<th scope="row">Row I</th>
<td>Open</td>
<td>Open</td>
<td>Open</td>
</tr>
<tr class="sortme">
<th scope="row">Row II</th>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
</tr>
<tr class="sortme">
<th scope="row">Row III</th>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
</tr>
</table>
jquery:
$(function() {
$( "tbody" )
.sortable({items: "tr.sortme" });
});
EDIT: I have solved this with DataTables. It will do both row and column reordering simultaneous. (Working codepen.) The usage was incredibly simple. Read the basic installation instructions to find out what scripts you need, download them (make sure to check 'ColReorder' and 'RowReorder' under the 'extensions' section)and then initialize your table as follows:
<script>
$(document).ready( function () {
$('#myTable').DataTable({
searching: false,
ordering: false,
rowReorder: true,
colReorder: true,
});
});
</script>
It was that simple. Note, I have given the 'searching' and 'ordering' options as false because I don't want those features in the table in my situation - you do not need to supply those, and you might find those features useful.
Something important to keep in mind: The HTML posted above will not work with DataTables. There are 2 problems with it. (1) Using tags within the rows (as row labels, or example where I'd written <th scope="row">Row III</th>) will not work. Instead, I turned those to tags, then it worked. (2) Additionally, your table must have a <thead> and <tbody> for DataTables to work (See this section of the install guide which mentions that.).
Finally, I'd like to mention that I've found it useful to provide the following option when initializing DataTables:
rowReorder: {
update: false
},
Apparently, the 'update' option can cause some undesirable behavior for certain tables. For my simple table, I noticed that unless I set this as false, I could only move the rows up and down by one row, no matter how far I dragged it. Setting it as false fixed that issue without causing any issues.
Consider the following.
$(function() {
function moveColumn(table, sourceIndex, targetIndex) {
console.log("Move Col " + sourceIndex + " to " + targetIndex);
var body = $("tbody", table);
$("tr", body).each(function(i, row) {
$("td", row).eq(sourceIndex).insertAfter($("td", row).eq(targetIndex - 1));
});
}
$(".mytable > thead > tr").sortable({
items: "> th.sortme",
start: function(event, ui) {
ui.item.data("source", ui.item.index());
},
update: function(event, ui) {
moveColumn($(this).closest("table"), ui.item.data("source"), ui.item.index());
$(".mytable > tbody").sortable("refresh");
}
});
$(".mytable > tbody").sortable({
items: "> tr.sortme"
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="mytable">
<caption>My Table</caption>
<thead>
<tr>
<td id="corner"></td>
<th scope="col" class="sortme">Col I</th>
<th scope="col" class="sortme">Col II</th>
<th scope="col" class="sortme">Col III</th>
</tr>
</thead>
<tbody>
<tr class="sortme">
<th scope="row">Row I</th>
<td>Open</td>
<td>Open</td>
<td>Open</td>
</tr>
<tr class="sortme">
<th scope="row">Row II</th>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
</tr>
<tr class="sortme">
<th scope="row">Row III</th>
<td>Open</td>
<td>Open</td>
<td>Closed</td>
</tr>
</tbody>
</table>
This is a basic example. There are some pitfalls, like there is not a good placeholder for the Columns, where the Rows will have one.

Sort DataTable by week and day

I use jQuery datatables to build up the table that shows project progress in the following format:
Project |Stage |Start |Finish
____________________________________
project 1 |stage 1 |W1D1 |W2D2
project 1 |stage 2 |W2D3 |W4D5
...
Project milestones are measured in the form 'W_D_' (Week, Day).
The problem is when I start sorting by column Start or Finish it doesn't work properly.
My code so far:
HTML:
<table id="projectStatus">
<thead>
<tr>
<th>Project</th><th>Stage</th><th>Start</th><th>Finish</th>
</tr>
</thead>
<tbody>
<tr>
<td>project 1</td><td>stage 1</td><td>W1D1</td><td>W2D2</td>
</tr>
<tr>
<td>project 1</td><td>stage 2</td><td>W2D3</td><td>W11D5</td>
</tr>
<tr>
<td>project 1</td><td>stage 3</td><td>W11D6</td><td>W5D6</td>
</tr>
</tbody>
</table>
JS:
$('#projectStatus').DataTable({
orderable: true,
processing: true,
defaultContent: '',
pageLength: 10
});
How do I fix that sorting issue? Thank you.
Since your data has numeric nature, I'm afraid, you can't benefit from data-order/data-sort attributes of corresponding table cells which will sort your rows alphabetically.
The way out (without loading extra plug-in) is to set up your own custom data type (say 'weekday') and corresponding sorting method for that:
//init DataTable
$('#projectStatus').DataTable({
//set data type 'weekday' for columns 2, 3
columnDefs: [{
targets: [2,3],
type: 'weekday'
}]
});
//turn 'week+day' string into number of days
const weekDay2Num = str => ([week, day] = str.match(/W(\d+)D(\d+)/).slice(1), week*7+day);
//specify sorting method for type 'weekday'
Object.assign($.fn.DataTable.ext.oSort, {
'weekday-asc': (a,b) => weekDay2Num(a)-weekDay2Num(b),
'weekday-desc': (a,b) => weekDay2Num(b)-weekDay2Num(a)
});
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<table id="projectStatus">
<thead>
<tr>
<th>Project</th><th>Stage</th><th>Start</th><th>Finish</th>
</tr>
</thead>
<tbody>
<tr>
<td>project 1</td><td>stage 1</td><td>W1D1</td><td>W2D2</td>
</tr>
<tr>
<td>project 1</td><td>stage 2</td><td>W2D3</td><td>W11D5</td>
</tr>
<tr>
<td>project 1</td><td>stage 3</td><td>W11D6</td><td>W5D6</td>
</tr>
</tbody>
</table>
You should provide the wrong results.
What I see is that you have string values, which are not treated as numbers. E.g., W11D5 is shown before W2D3.
Try to use the data-order attribute, concatenating week and day:
<td>project 1</td>
<td>stage 2</td>
<td data-order="23">W2D3</td>
<td data-order="115">W11D5</td>
If it still doesn't work, zero-pad it:
<td>project 1</td>
<td>stage 2</td>
<td data-order="023">W2D3</td>
<td data-order="115">W11D5</td>
You can add the data-order attribute to the cells. DataTables will use this value to order your rows instead of the text inside. You can concatenate the Week and Day in this attribute.
<table id="projectStatus">
<thead>
<tr>
<th>Project</th><th>Stage</th><th>Start</th><th>Finish</th>
</tr>
</thead>
<tbody>
<tr>
<td>project 1</td><td>stage 1</td><td data-order="11">W1D1</td><td data-order="22">W2D2</td>
</tr>
<tr>
<td>project 1</td><td>stage 2</td><td data-order="23">W2D3</td><td data-order="115">W11D5</td>
</tr>
<tr>
<td>project 1</td><td>stage 3</td><td data-order="116">W11D6</td><td data-order="56">W5D6</td>
</tr>
</tbody>
</table>

Why is my datatable adding a blank row?

I am hitting a controller and passing back an array which i loop through and then pass into a datatable.
When i first pass data into the datatable, for some reason it is adding a blank row, although if i then clear the table, and add exactly the same data, it doesn't.
I'm not doing anything fancy, just a really basic DT.
for (i = 0; i < data.length; i++) {
$('#workcarriedouttable').dataTable().fnAddData([
data[i].DateStarted,
data[i].TimeStarted,
data[i].DateEnded,
data[i].TimeEnded,
data[i].WorkDetails,
data[i].WorkCost
]);
}
I have stepped through my code and the array does not contain any blank records, so i assume this is happening only when the DT is first initialized.
Which is simply
$('#workcarriedouttable').dataTable()
Table structur
<table id="workcarriedouttable" class="display">
<thead>
<tr>
<th style="width:30px;">Date Start</th>
<th style="width:30px;">Time Start</th>
<th style="width:30px;">Date End</th>
<th style="width:30px;">Time End</th>
<th style="width:240px;">Details</th>
<th style="width:30px;">Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Anyone know of a fix for this?

CSS an javascript gone after I click on a button

Currently I have a problem on all the pages.The page contains a form with a submit button and a table that contains buttons.The problem is whenever I click on edit button from the table the cssandjavascript are gone.
Here is jascript code
<script type="text/javascript">
$(document).ready(function() {
var table = $('#datatable').dataTable();
var tableTools = new $.fn.dataTable.TableTools(table, {
'aButtons' : [ ],
'sSwfPath' : 'js/copy_csv_xls_pdf.swf'
});
$(tableTools.fnContainer()).insertBefore('#datatable_wrapper');
});
</script>
The table
<table id="datatable" class="hover" >
<thead>
<tr>
<th width="80">Poll ID</th>
<th width="120">Poll Name</th>
<th width="120">Poll Description</th>
<th width="120">poll publisher</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
<th width="60">Voter</th>
<th width="60">Afficher courbe</th>
</tr>
</thead>
<tfoot>
<tr>
<th width="80">Poll ID</th>
<th width="120">Poll Name</th>
<th width="120">Poll Description</th>
<th width="120">poll publisher</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
<th width="60">Voter</th>
<th width="60">Afficher Courbe</th>
</tr>
</tfoot>
<c:forEach items="${listpolls}" var="poll">
<tbody>
<tr>
<td>${poll.id_poll}</td>
<td>${poll.titre}</td>
<td>${poll.description}</td>
<td>${poll.emp_login}</td>
<td>Edit</td>
<td>Delete</td>
<td>Vote</td>
<td>Afficher courbe</td>
</tr>
</c:forEach>
</tbody>
</table>
Here is an picture of the table before i click on edit.
And now
As you can see css and javascipt code are both gone.
What am I doing wrong here? Any help is much appreciated.
Problem is the /poll/edit/... etc. in link's href. Even if redirected, browser still thinks you're in different directory from where relative paths to your styles & scripts won't work.
Specify base directory for all links on page:
<base href="http://www.domain.com/somebasedir/" />
Then regardless of the redirection, for example this stylesheet:
<link rel="stylesheet" type="text/css" href="path/style.css" />
should always be looked for in:
/somebasedir/path/style.css

How can I make my dynamic JSP table scrollable and sortable in ascending and descending order?

I want to display data from a database in a JSP table dynamically. I'd like to make my table scrollable, sortable (ascending and descending), searchable and paginatable.
See this link for example; you'll find a table with sortable columns, search functionality and paginating.
I would like to achieve something similar to that datatable.
The JSP page looks like this
<html>
<body>
<div class="container" style="overflow:scroll;
height:250px;width:100%;overflow:auto">
<TABLE id="example" class="table table-striped">
<thead>
<TR valign=top class="header">
<TH bgcolor="#008000">ATM Site No</TH>
<TH bgcolor="#008000">ATM Location</TH>
<TH bgcolor="#008000">LHO</TH>
<TH bgcolor="#008000">Cash</TH>
<TH bgcolor="#008000">Non Cash</TH>
<TH bgcolor="#008000">Revenue</TH>
<TH bgcolor="#008000">Up Time</TH>
<TH bgcolor="#008000">Up Time Date</TH>
</TR>
</thead>
<s:iterator value="uptimeBeans">
<tbody>
<TR valign=top>
<TD><s:property value="ATM_Site_No"/></TD>
<TD><s:property value="ATM_Location"/></TD>
<TD><s:property value="LHO"/></TD>
<TD><s:property value="Cash"/></TD>
<TD><s:property value="Non Cash"/></TD>
<TD><s:property value="Revenue"/></TD>
<TD><s:property value="Up Time"/></TD>
<TD><s:property value="Up Time Date"/></TD>
</TR>
</tbody>
</s:iterator>
</TABLE>
</div>
</body>
</html>
You just need to call this script for using datable after adding jquery and datatable js :-
$(document).ready(function() {
$('#example').dataTable( {
"scrollY": 200,
"scrollX": true,
"order": [[ 1, "desc" ]]
} );
} );
Here, 1 is column no. needed to sort , you can change it as per need.
Refer datatable intialization
datatable sorting
datatable scrolling
Use this script for dynamic sorting in datatable.
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 3, "desc" ]]
} );
} );
please refer this URL for dynamic sorting in datatable:
https://datatables.net/examples/basic_init/table_sorting.html

Categories