Know selected row with responsive datatables - javascript

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);
});

Related

checkbox click event with jquery datatables not working

I have used jQuery Datatables https://datatables.net/ for my grids.
There are two grids, each has a checkbox in the grid. I need to generate an event when checkbox is checked/unchecked.
I have tried this but it doesn't work. Please let me know what I am doing wrong here..........
$(document).ready(function () {
$('.cBSAGrid tr td').click(function (event) {
alert('0');
});
});
and
$(document).ready(function () {
$('#BSAGrid tr').click(function (event) {
alert('0');
});
});
My datatable jquery
$.ajax({
type: "POST",
url: "/BSA/BSAExceptionGrid",
data: '{ policynumber: "' + txtpolicy.val() + '",clientname:"' + clientname.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
div.css("display", "none");
$('#BSAGrid').DataTable({
paging: false,
searching: false,
destroy: true,
"bInfo" : false,
data: response,
columns: [
{ "data": "Logged_ID" },
{ "data": "Logged_ID" },
{ "data": "CustomerName" },
{ "data": "ClientType" }
],
aoColumnDefs: [
{
aTargets: [0], // Column number which needs to be modified
mRender: function (o, v) { // o, v contains the object and value for the column
return '<input type="checkbox" id="chkBSA" name="chkBSA" />';
}
//,sClass: 'tableCell' // Optional - class to be applied to this table cell
}
,
{
aTargets: [1],
visible: false
}
],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
},
failure: function (response) {
alert(response);
},
error: function (response) {
alert(response.responseText);
}
});
HTML
<div id="BSAGridContainer" style="display:none;">
<table id="BSAGrid" class="cBSAGrid table table-responsive">
<thead>
<tr>
<th></th>
<th >Logged_ID</th>
<th>Client Name</th>
<th>Client Type</th>
</tr>
</thead>
</table>
</div>
Try bellow code:
$(document).ready(function(){
$(document).on("change", "#chkBSA", function() {
alert('click')
});
});
You could include the onChange event listener in the same column adding this into your column return text onChange="gridCheckboxChange(this);"
If you're using bootstrap 4 custom-checkbox then add a class into your checkbox
.className {left: 0;z-index: 1;width: 1.25rem;height: 1.25rem;}

jquery/javascript are not working inside ng-view

I'm trying to achieve SPA with help angular route provide for that i'm using ng-view for injecting the views. in one page i'ave a jquery datatable where i need to get the index of row selected by using jquery. but this is not happing inside ng-view. i tried by using directives also but no luck.
can someone help me in this
Home.html
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
Get Selected Rows
Controller.Js:
app.controller("HomeController", function ($scope, $http,$window) {
$('#example').DataTable({
"ajax": {
"url": "test.json",
"dataSrc": ""
},
"columns": [
{ "data": null },
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
$scope.$broadcast('dataloaded');
$scope.Customers = $("example").DataTable().data;
console.log("Result: ", $scope.Customers.length);
$scope.GetDetails = function () {
var table = $("example").DataTable();
var rowid = table.row(this).index();
alert(rowid);
};
$scope.GetRowID = function () {
$('#example tbody').on('click', 'tr', function () {
console.log("inside");
debugger;
var table = $("#example").DataTable();
alert('Row index: ' + table.row(this).index());
});
};
$scope.init();

DataTable ajax Nested Table with search

I have created jQuery DataTable with ajax which is working fine but I need to add another nested table inside it and it should be search from parent table. Is it possible !!
HTML
<table id="gatePass" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Company Name</th>
<th>From Date</th>
<th>To Date</th>
<th>Area</th>
<th>Status</th>
<!--<th style="display:none">itemId</th>-->
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript
var dataTableExample = 'undefined';
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
var a = "/_api/lists/getbytitle('GatePass')/items?$select=Id,Title,FromDate,ToDate,Area,OtherOldBuildingArea,OtherNewBuildingArea,WFStatus&$filter=WFStatus eq 'Approved'";
$.ajax({
url: a,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample = $("#gatePass").DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ mData: "Title" },
{
mData: "FromDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{
mData: "ToDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{ mData: "Area" },
{ mData: "WFStatus" },
]
});
}
function myErrHandler(data, errCode, errMessage) {
alert("Error: " + errMessage);
}
What is good for nested table to get data directly from ajax or to make dynamic string and to the table. Issue is if I make dynamic string than I think I cannot search on it. Please help me.

Disable row selection in first column DataTables

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>.

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