Disable row selection in first column DataTables - javascript

I have a simple datable https://jsfiddle.net/ptwgxpzu/27/
JS:
var dataSet = [
["data/rennes/", "Rennes", "rennes.map"],
["data/nantes/", "Nantes", "nantes.map"],
["data/tours/", "Tours", "tours.map"],
["data/bordeaux/", "Bordeaux", "bordeaux.map"],
["data/limoges/", "Limoges", "limoges.map"],
["data/troyes/", "Troyes", "troyes.map"]
];
var table = $('#maptable').DataTable({
"data": dataSet,
"paging": false,
"columns": [{
title: "Download"
}, {
title: "Name"
}, {
title: "File Name"
}],
"columnDefs": [{
"targets": [0], // Download
"visible": true,
"searchable": false,
"bSortable": false
}, {
"targets": [1], // Name
"visible": true,
"searchable": true
}, {
"targets": [2], // File name
"visible": true,
"searchable": true
},
],
"order": [
[1, "asc"]
],
"oLanguage": {
"sSearch": ""
},
"aoColumns": [{
"title": ' <i class="fa fa-cloud-download white"></i> Download',
"render": function(data, type, full, meta) {
var url = 'http://localhost/';
var mapurl = url + full[0] + full[2],
trackurl = url + full[0] + full[2].replace('map', 'trx');
return '<div class="btn-group">' +
'<button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' +
'<i class="fa fa-cloud-download white"></i> <span class="caret"></span>' +
'</button>' +
'<ul class="dropdown-menu">' +
'<li></i> map file</li>' +
'<li></i> track file</li>' +
'</ul>' +
'</div>';
}
}, {
"title": "Name"
}, {
"title": "File name"
}]
});
$('#maptable tbody').delegate( 'tr', 'click', function () {
$(this).toggleClass('selected');
//...
});
HTML:
<body>
<br />
<div class="container">
<table id="maptable" class="table table-bordered" width="100%"></table>
</div>
</body>
When rows in table not selected and I click on dropdown button in first column - row in table is becoming selectable.
And when row in table selected and I click on dropdown button in first column - row in table is becoming deselected
How avoid action of 'deselected row' when I click on dropdown button when row in table selected and avoid action 'selected row' when I click on dropdown button when rows in in table not selected? Or disable row selection only in first column

Use the following code:
$('#maptable tbody').on('click', 'td:not(:first-child)', function () {
$(this).closest('tr').toggleClass('selected');
//...
});
See updated jsFiddle for code and demonstration.
Alternatively, if you want allow selection in the first column (except when the button is clicked), then use the following code:
$('#maptable tbody').on('click', 'tr', function (e) {
if(!$(e.target).is('button')){
$(this).toggleClass('selected');
}
//...
});
See updated jsFiddle for code and demonstration.

Row selection in DataTables uses the select extension.
$('#yourTableId').DataTable({
select: true
});
If you want full control over which columns allow selection, use select.selector. For this question, ignore selection events when the first column is chosen, use:
$('#yourTableId').DataTable({
select: {
selector:'td:not(:first-child)',
style: 'os'
}
});
Be sure to include an extra empty <th> element when defining your table, e.g.:
<table id="yourTableId" class="display">
<thead>
<tr>
<th></th>
#foreach(string column in Model.columns) {
<th>#column</th>
}
</tr>
</thead>
<tfoot>
<tr>
<th></th>
#foreach(string column in Model.columns) {
<th>#column</th>
}
</tr>
</tfoot>
</table>
Here I use Microsoft Razor (the #foreach)for brevity, but regardless of your platform, notice the <th></th> just after the <tr>.

Related

How to reload data in existing dataTable()?

I have table that is already displayed on the screen. If user added new row or edit existing row then new set of data will be returned with the ajax. Once data is retrieved I want to clear the existing records from tbody and refresh/reload dataTable . Here is example of my code:
var statusData = {
479664: {
"author": "JH2423",
"up_to": "09/30/2017",
"status": "Closed",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Slow",
"status_id": "479664"
},
479665: {
"author": "KK2342",
"up_to": "09/30/2017",
"status": "Approved",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Close",
"status_id": "479664"
},
479666: {
"author": "DD7822",
"up_to": "09/30/2017",
"status": "Close",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Process",
"status_id": "479666"
},
479667: {
"author": "YU8343",
"up_to": "09/30/2017",
"status": "Declined",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Warrning",
"status_id": "479667"
},
479668: {
"author": "MMSD3",
"up_to": "09/30/2017",
"status": "Participating",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Approved",
"status_id": "479668"
}
};
buildDataTable('tbl-status', false, 2, false, true, true, []);
function buildDataTable(tblID, lengthChange, pageLen, searchBar, infoSection, pagingInfo, arrOrder) {
var table = $("#" + tblID),
arrSort = [];
if (arrOrder.length) {
arrSort.push(arrOrder); // arrOrder example: [1, "desc"] or [4, "asc"]. First element is column (first col starts from 0) and second is order by direction.
}
$(table).DataTable({
lengthChange: lengthChange,
pageLength: pageLen,
lengthMenu: [
[10, 15, 20, 25, 50, -1],
[10, 15, 20, 25, 50, "All"]
],
order: arrSort,
searching: searchBar,
info: infoSection,
paging: pagingInfo
});
}
$("#load").on("click", function() {
var container = $("#status-container"), // Clear out existing table.
table = $("<table>").addClass("table").prop("id", "tbl-status"),
thead = $("<thead><tr><th>Reason</th><th>As Of</th><th>Up To</th><th>Author</th><th>Date</th><th>Status</th><th class='text-center'>Status</th></tr></thead>"),
tbody = $("<tbody>");
if ($.isEmptyObject(statusData)) {
var tr = $('<tr><td colspan="7">No records were found.</td></tr>');
tbody.append(tr);
} else {
for (key in statusData) {
var btnName = statusData[key].current == true ? "Change" : "Edit";
var tr = $('<tr>');
tbody.append(tr);
tr.append($('<td>').text(statusData[key].reason));
tr.append($('<td>').text(statusData[key].as_of));
tr.append($('<td>').text(statusData[key].up_to));
tr.append($('<td>').text(statusData[key].author));
tr.append($('<td>').text(statusData[key].date));
tr.append($('<td>').text(statusData[key].status));
tr.append($('<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="' + statusData[key].status_id + '" data-current="' + statusData[key].current + '"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> ' + btnName + '</button></td>'));
}
}
$("#tbl-agency-status").remove(); // Remove existing table.
table.append([thead, tbody]);
container.append(table);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.html5.min.js"></script>
<button type="button" name="load" id="load">Load New Data</button>
<div class="card mt-4">
<div class="card-header card-bg-custom">
<h5 class="text-center">Status</h5>
</div>
<div class="card-body">
<div class="table-responsive" id="status-container">
<table class="table" id="tbl-status">
<thead>
<tr>
<th>Reason</th>
<th>As Of</th>
<th>Up To</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Failure</td>
<td>09/11/2019</td>
<td>10/31/2019</td>
<td>System</td>
<td>10/01/2019</td>
<td>Conditional</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505552" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button></td>
</tr>
<tr>
<td>Initial</td>
<td>06/12/2017</td>
<td>09/30/2017</td>
<td>MM434</td>
<td>06/23/2017</td>
<td>Participating</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="479664" data-current="false"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
</tr>
<tr>
<td>Reporting</td>
<td>07/11/2019</td>
<td>08/31/2019</td>
<td>System</td>
<td>10/01/2019</td>
<td>Testing</td>
<td class="text-center"><button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="505551" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
For some reason current data is not removed. I would like to remove all existing data and reload new data in the table. If anyone have suggestion please let me know.
<script> //I usually put the script section at the end of head tag
var table_1; //declare your table var here and initialize as a datatable inside document ready below.
$(document).ready(function() {
table_1 = $('#table_1').DataTable( {
dom: "Bfrtip",
ajax: {
url: "/get-data", //path where json data will be served from. ex: get-data.php or my-data.json
type: "POST" //use POST to not have to deal with url encoding various characters
},
serverSide: true,
searchDelay: 2000, // use this to throttle ajax requests when typing in search input
processing: true, // optional visual indicator that a search has been sent to backend
lengthMenu: [ 10, 25, 50, 75, 100 ], // define per page limits. first value will be the default
buttons: [
"pageLength" // per page drop down button. i usually override/extend the default button
],
columns: [ // column definitions of json data fields
{ data: "status_id", title: "ID", width: "1%" }, // width:1% makes col width as small as possible
{ data: "status", title: "Status(hidden)", visible:false }, //visible:false hides column but allows you access to field data
{ data: "reason", title: "Reason and Status", render: function ( data, type, row ) { //render allows combining of fields into single column
return data + ' <small>('+row.status+')</small>'; // data will be reason value. row.status is how you reference status value
} },
{ data: "current", title: "Current", searchable:false }, //searchable: false set this field to not be used in search
{ data: null, title: "Button", render: function ( data, type, row ) { // use data:null if you need to render stuff in a column that does not necessarily need to be tied to a specific data value
if(row.current){
return '<button type="button" class="btn btn-secondary btn-sm status-edit" data-recid="'+ row.status_id +'" data-current="true"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Change</button>';
}
else{
return '<button>Different Button</button>';
}
} },
],
rowId: 'status_id' //sets the tr row id to the value in this column. useful for DOM and other manipulation later
} );
}
</script>
<table id="table_1" class="table table-striped table-bordered table-sm" style="width:100%"></table>
<!-- If you define the title attributes in json column definitions above
then you don't need to create html table headers/footers.
Just an empty table tag will do. -->
Your ajax url will need to return data as JSON format with an array of objects:
[
{
"author": "KK2342",
"up_to": "09/30/2017",
"status": "Approved",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Close",
"status_id": "479664"
},
{
"author": "DD7822",
"up_to": "09/30/2017",
"status": "Close",
"as_of": "06/12/2017",
"date": "06/23/2017",
"current": false,
"reason": "Process",
"status_id": "479666"
}
]
To get started create a file named testing.json with the above contents. Then replace table_1 ajax-url from above example to '/your_folder_path/testing.json'. This datatable should now load.
To get access to the data all you need to do is call:
table_1.data(); // datatables object
//OR
table_1.data().toArray(); // a simple array of objects with each rows data you can loop through
Docs on manipulating data for every row can be found here: https://datatables.net/reference/api/row().data()
After data has been modified you can table_1.draw() or table_1.reload() as #NawedKahn suggested - depending on your use case.
Tons of useful functionality can be found in Docs below
Everything you can do with datatables objects:
https://datatables.net/reference/api/
All datatables options:
https://datatables.net/reference/option/
Browse through these links before you try to build any sort of functionality, it probably already exists.

Copy Row Table into 'New Table'. | jQuery

I have created a dataTable copy row.
mainTable can only copy to the secondTable.
The problem is when adding New Table,
&
i want the mainTable row can copy into New Table.
i already create "Create New Table" button
New table will append into parent div allTable
MY JSFiddle.
Reference :
I want copy row into selected table(secondTable/newTable). not multiple. and I dont know how to add the selected button, because I'm using a variable.
I have parent div class="allTable" for Table/children (mainTable,
secondTable, and New Table).
i have "COPY ROW" for copy row table from mainTable to another Table, but now only work to copy into the secondTable.
In the $(document).ready(function()),
I have created dataTable for mainTable and secondTable.
mainTable ID is #table1
secondTable ID is #table2
New Table ID is #newTable + index (newTable(3) )
New Table will display blank data.
SCREENSHOT :
I really hope for your help.
This works, but you can improve it, I hope you can get the idea from here, this is not fully working as intended but the flow might help you.
https://jsfiddle.net/o6ysgzps/26/ I have updated the fiddle,
as you can see, I collected the list of tables that are created, and looped to each tables with a confirmation box to select which table you want it to be copied to., You can use bootstrap modal and jquery confirm to make it better,
You can make it cleaner,
html
<body>
<select id='cboList' style=''></select>
<div class="allTable">
<div class="one" style="padding-bottom:50px">
<h2>TABLE 1</h2>
<table id="table1" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<button id="Copy">COPY ROW »</button>
<!-- <button id="LeftMove" style="float:left;">« left</button> -->
<br>
<h2>TABLE 2</h2>
<div class="two">
<table id="table2" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<br>
<br>
<br>
<input type="button" class="submitButton" value="Create New Table">
<h2>NEW TABLE GOES HERE</h2>
</div>
</body>
This is the js
$(document).ready(function() {
var mainTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
}); // mainTable
var secondTable = $('#table2').dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // secondTable
mainTable.on('click', 'tbody tr', function() {
$(this).toggleClass('selected');
});
$('#Copy').on('click', function() {
var tables = $(".allTable").find("table*[id]").not("#table1");
tables.each(function(){
console.log(this.id);
var tbl_id = this.id;
var $elem = $(this);
var r = confirm("Copy to table "+tbl_id+"?");
var table_to_copy = $elem.dataTable();
if (r == true) {
copyRows(mainTable, table_to_copy);
alert("Copied!");
} else {
}
});
//
});
}); // end of $(document).ready...
function copyRows(fromTable, toTable) {
var $row = fromTable.find(".selected");
$.each($row, function(k, v) {
if (this !== null) {
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow); // <-- Copy Row
// fromTable.fnDeleteRow(this); <-- Move row, delete main row.
}
});
}
var tableIndex = 3;
$('.submitButton').click(function() {
let addIndex = tableIndex++;
var addTable = '<div class="newTable'+ addIndex +'">' +
'<table id="newTable'+ addIndex +'" class="table table-bordered table-hover">' +
'<thead>' +
'<tr>' +
'<th></th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'</tr>' +
'</thead>' +
'</table>' +
'</div>';
$('.allTable').append(addTable);
var newTable = $("#newTable"+ addIndex).dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"scrollY": "200px",
"scrollCollapse": "true"
}); // newTable
});
modify your code as follow:
function copyRows(fromTable, toTable) {
var toTable = $("table:last").dataTable(); // add this line to the function. Then you can remove toTable from parameters

On row click , prevent to redirect when clicking on the button

Here I am using data table
Row click I want to do something [redirection],
in a row, one of the columns has a button & it has some action.
Problem: when I click button to do action getting row click, want to prevent row click while clicking on button
CODE
$('#example').click(function () {
var dataArr;
var rows = $('tr.selected');
var rowData = table.rows(rows).data();
$.each($(rowData), function (key, value) {
dataArr = value["id"];
window.location = 'clients?id=' + dataArr;
});
}
What should I change? Thank you
Edit:
The buttons :
$(document)
.ready(
function() {
var table = $('#example')
.DataTable({
"sAjaxSource": "/clients",
"sAjaxDataProp": "",
"order": [
[0, "asc"]
],
"aoColumns": [{
"mData": "id"
},
{
"mData": "name"
},
{
"mData": "lastName"
},
{
"mData": null,
defaultContent:'<p>1</p>'
},
{
"mData": null,
className: "center",
defaultContent: ' <p title="New"><button class="btn btn-primary btn-xs newButton" data-title="Add" id="btn"><span class="glyphicon glyphicon-plus"></span></button></p>'
},
{
"mData": null,
className: "center",
defaultContent: '<p data-placement="top" data-toggle="tooltip" title="Edit "><button class="btn btn-default btn-xs data-title="edit" data-toggle="modal" data-target="#edit""><span class="glyphicon glyphicon-pencil"></span></button></p>'
},
{
"mData": null,
className: "center",
defaultContent: ' <p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete"><span class="glyphicon glyphicon-trash"></span></button></p>'
}
]
});
I am using DataTables. ANd only need this for the last two columns where edit and delete are
Whenever child event call parent event, here you can prevent using the following method.
event.stopPropagation();
Try using event.stopPropagation();
The code will be similar with :
$(".table_row"/*the table row class*/).on('click', 'button', function () {
//button action
}).on('click', $(this).parent().parent().parent() , function (e) {
e.stopPropagation();
});/* if $(this).parent().parent().parent() doesn't work ,search in developer tools to see where click action is triggered ,on the */
Something like
I tried to make something I don't know if you like it but it works the way you want this(updated).

Know selected row with responsive datatables

I have a problem with responsive datatables. When I resize the window and button was hidden this code, used to know which row is selected, doesn't work:
$('#usersTable tbody').on( 'click', 'button', function () {
usernameSelected = (userTable.row( $(this).parents('tr') ).data().username);
} );
Maybe the problem is on parents('tr'), but how can I get information when table was resized? I use the returned value to recognize the button of which row is clicked. My table use ajax call like this:
if ( ! $.fn.DataTable.isDataTable( '#licensesTable' ) ) {
licenseTable = $('#licensesTable').DataTable({
responsive: true,
//disable order and search on column
columnDefs: [
{
targets: [4,5],
orderable: false,
searchable: false,
}
],
//fix problem with responsive table
"autoWidth": false,
"ajax": "table",
"columns": [
{ "data": "user" },
{ "data": "startDate",
"render": function (data) {
return (moment(data).format("DD/MM/YYYY"));
}
},
{ "data": "endDate",
"render": function (data) {
return (moment(data).format("DD/MM/YYYY"));
}
},
{ "data": "counter" },
{ data:null, render: function ( data, type, row ) {
return '<button type="button" class="btn btn-primary" id="updadteLicense" data-toggle="modal"'
+'data-target="#updateLicenseModal">Update</button>'
}
},
{ data:null, render: function ( data, type, row ) {
return '<button type="button" class="btn btn-danger" id="deleteLicense" data-toggle="modal"'
+'data-target="#deleteLicenseModal">Delete</button>'
}
}
],
});
}
else {
licenseTable.ajax.url("table").load();
}
This is the HTML code relative datatable:
<table id="licensesTable"
class="table table-bordered table-striped">
<thead>
<tr>
<th>User</th>
<th>Start date</th>
<th>Expire date</th>
<th>Max execution</th>
<th>Delete</th>
<th>Update</th>
</tr>
</thead>
</table>
I dont know if this is a good way, but i solved it by adding id to the button.
in Laravel
->addColumn('Datalist',function($loadData){
return '<center><button id='.$loadData->rowID.' type="button" class="btn-showdata"><i class="fa fa-list"></i></button></center>';
})
in javascript:
$(this).on('click','#tableid .btn-showdata',function(){
console.log(this.id);
});

DataTables hyperlink on all rows in a column

I am using DataTables to generate a table. There is a column containing order numbers.
For example:
...
I need every row in this column to have a hyperlink to view/order?id=? where ? is the contents of row in the Order No column. For example the first row would be a hyperlink to view/order?id=1321755 etc.
What is the simplest way I can do so?
Here is the code that I am using to initialize the DataTables:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"serverSide": true,
"ajax": {
"url": "../server_processing/orders.php",
"type": "POST"
},
"order": [[ 0, "desc" ]]
} );
} );
</script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order No</th>
...
</tr>
</thead>
<tbody>
</tbody>
</table>
Check this out:
http://datatables.net/reference/option/columns.render
You can add a column render callback when you specify columns definition.
var columnsDef = [
...
{
"title": "Order No.",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
...
];
$("#table").dataTable({
...
"columns": columnsDef,
...
});
The data in that column will be changed to what the render function return.
I needed to use jQuery dataTables and turn a normal field to be a HREF field.
Here you have it all, including also dataTables error handling..
Enjoy..
Yosi Lev
1) The HTML part:
<!-- COMPANIES LIST start -->
<div id="compListDiv" style="visibility:hidden; position : absolute; left : 360px; top : 40px;">
<br>
<table id="compList" align="left" border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
</thead>
</table>
</div>
<!-- COMPANIES LIST end -->
2) The javascript dataTables part:
When a button is clicked the following js function is called:
function companiesList(){
accountstable=$('#compList').dataTable({
sort : true,
bFilter: false,
bInfo: false,
paging:false,
autoWidth: true,
ajax: {
url: "http://localhost:8080/j112/rest-1/companies/list",
dataType: 'json',
dataSrc: "data",
error: function ( xhr, textStatus, error ) {
if ( textStatus === 'timeout' ) {
alert( 'Timout error. The server took too long to send back the data.\nPlease try again.' );
}
else {
alert( 'User Not In Session.' );
location.href = "login.html";
}
myDataTable.fnProcessingIndicator( false );
}//function
}/* ajax: */,
scrollCollapse: true,
bDestroy: true,
serverSide:true,
fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { // this function is called for each row, but I could not use it to add the link
// if ( aData[1] == "A" )
//var td0 = $('td:eq(0)', nRow)[0];
// $('td:eq(0)', nRow).html( 'A');
// $('td:eq(0)', nRow).html( '<b>A</b>' )
},// fnRowCallback
initComplete : function(settings, json) { // this function is called after table is populated
//$("#compListDiv").show(); // this did not work so I used regular js to show the DIV
var d1 = document.getElementById('compListDiv');
d1.style.visibility = 'visible';
}, //initComplete
"columnDefs": [
{ "width": "10%", "targets": 0 },
{ "width": "20%", "targets": 0 },
{ "width": "70%", "targets": 0 }
],
"columns":[
//{"data" : "id"},
{ // render
"data": function (data, type, row, meta) {
return '' + data.id + '';
}
},
{"data" : "name"},
{"data" : "address"}
]
}); // dataTable()
}// companiesList()
By Yosi Lev - Feb 22, 2016

Categories

Resources