I'm using this data table.
I need to get both ProductID & ProductStatus from the selected row where ProductID is embedded in the TR ID of each row.
I'm not displaying the productStatus in the table. But I need to get the status when the row is selected. Where can i add them ?
Please Guide me ....
CODE
function loadClick() {
const databaseRef = firebase.database().ref('S01/Products');
var query = databaseRef.orderByKey().startAt("C09M03S03").endAt("C09M03S04").limitToFirst(6);
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var t = $('#products_table').DataTable();
var key = childSnapshot.key;
var MID = childSnapshot.child("productMID").val();
var SID = childSnapshot.child("productSID").val();
var ProductID = childSnapshot.child("productID").val();
var name = childSnapshot.child("productName").val();
var unit = childSnapshot.child("productUnit").val();
var productMRP = childSnapshot.child("productMRP").val();
var price = childSnapshot.child("productSellingPrice").val();
var buying_price = childSnapshot.child("productBuyingPrice").val();
var productstatus = childSnapshot.child("productStatus").val();
var row = "";
t.row.add(['<td class="cell-60 responsive-hide"></td><td class="cell-300"><a class="avatar" href="javascript:void(0)"><img class="img-responsive" src="../../../global/portraits/1.jpg"alt="..."></a></td>', '<td>' + name + '</td>',
'<td>' + unit + '</td>', '<td tabindex="1">' + productMRP + '</td>', '<td tabindex="2">' + price + '<\/td>',
'<td tabindex="3">' + buying_price + '<\/td>']).node().id = ProductID;
t.draw(false);
});
});
}
function EditProdStatus(ProductID, ProductStatus) {
var statusRef = firebase.database().ref('S01/Products').child(ProductID).child("productStatus");
statusRef.set(!ProductStatus);
console.log("Product Status changed to " + ProductStatus);
}
$(document).ready(function () {
loadClick();
var table = $('#products_table').DataTable({
'columnDefs': [{
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
'targets': 3,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '1');
}
},
{
'targets': 4,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '2');
}
},
{
'targets': 5,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('tabindex', '3');
}
}
],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']]
});
});
function productDisable() {
var oTable = $('#products_table').dataTable();
$(".select-checkbox:checked", oTable.fnGetNodes()).each(function () {
console.log($(this).val());
});
}
HTML
<table id="products_table" class="table is-indent tablesaw" cellspacing="0" width="100%">
<thead>
<tr>
<th class="pre-cell"></th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="3">Product Name</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product Unit</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Product MRP</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Selling Price</th>
<th class="cell-300" scope="col" data-tablesaw-sortable-col data-tablesaw-priority="4">Buying Price</th>
</tr>
</thead>
</table>
jsFiddle Demo
For those td which you don't want to display in DataTable, you just need to provide Visible:false in your columnDefs. They will be hidden but you can retrieve their data if they are in selected rows.
$('#example').DataTable({
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}, {
"targets": [2],
"visible": false,
"searchable": false
}]
})
Another thing is you are using fnGetNodes which is a legacy function for datatable v1.9 on selection which is not going to work for DataTable 10.1. You can get selected rows as follow:
table.rows('.selected').data();
This is going to return selected rows even if you have selected multiple rows in different pages.
You can find a Demo here.
As you can see in demo that for Employees data, their position column in not visible in DataTable but its data is available while retrieving data of selected rows.
Documentation here for Hidden columns
Update
I have updated your Fiddle. Updated Fiddle .
Try this, it helps you
var table = $('#example').DataTable();
$('#example tbody').on( 'click', '.checkbox', function () {
if(this.checked==true)
{
console.log( table.row( this.closest('tr') ).data() );
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/js/jquery.dataTables.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>check</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkbox" ></td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox" ></td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
</tbody>
</table>
Try this ...
Add your productStatus column to the HTML :
'<td>' + productStatus + '</td>'
Let's say that's at column index 8. So add the following to the dataTables columnDefs :
{
'targets': 8,
'visible': false,
}
Now, in productDisable(), you can get productID & productStatus from each selected row as follows :
function productDisable() {
table.rows(".selected").every(function() {
var row = this.node();
var productID = row.id;
var productStatus = this.data()[8];
console.log(productID, productStatus);
// do whatever with productID and productStatus
});
}
Demo
I a using Datatable 1.10 and this Code is Working for me
"btnSubmit" is the Id of the Button when you click on the button selected checkbox data you will get
// Handle form submission event
$('#btnSubmit').on('click', function() {
//Hold the Object Data what are the checkbox selected
var tblData = table.api().rows('.selected').data();
var tmpData;
//Iterate the Object and extract you one one by one row data With Hidden Id Also
$.each(tblData, function(i, val) {
tmpData = tblData[i];
alert(tmpData);
});
})
//You can use this one.
$( $('#example').DataTable().$('.checked').map(function ()
{
return $(this).closest('tr');
//want to get attribute
//var id = $(this).closest('tr').find('td.Select').attr('id');
}));
Related
I have some issues in getting values from datatable that i imported from excel.
i Want to pass the rows that selected (at least can be viewed in alert), here's the case.
the value that i want is like
Name : A. Mused , No HP : 087....
Name : Aida Bugg, No HP : 089....
Name : Allie Grater, No HP : 087...
but the result is just like this screenshot :
result popup alert and data
here's the code :
html
#if (Model != null)
{
<table id="tablePenerima" class="table table-striped table-bordered animate__animated animate__fadeInRight" cellpadding="0" cellspacing="0">
<thead>
<tr>
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<th align="center">#col.ColumnName</th>
}
</tr>
</thead>
<tbody>
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr >
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<td align="center">#row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
}
and the javascript :
$(document).ready(function () {
var table = $('#tablePenerima').DataTable({
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone',
],
select: true
});
$('#tablePenerima tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnBlast').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
var data = $('#tablePenerima').DataTable().row('.selected').ids();
console.log(ids);
alert("Name:" + ids[0] + "\nNo HP:" + ids[2]);
});
});
I hope all of you can solve my problem because my knowledge in js is still weak. Thanks :)
I have no experience with DataTable package, but i think the problem is your map function. It returns the first row of selected rows.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
Instead of
return item[0]
You should return all selected rows;
return item
In $('#btnBlast').click event
Some one please guide me on how to change my table as dataTable.
My table will be loaded dynamically using below code.
$.post('geterpitem',{grn : $('#grn').val()}, function(responseJson) {
if(responseJson.length!=null){
var $tbl = $("#itemtable");
$tbody = $tbl.find('tbody');
$tbl.find("tr:gt(0)").remove();
var i = 1;
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).append(i);
rowNew.children().eq(1).text(value['itemcode']);
rowNew.children().eq(2).text(value['itemname']);
rowNew.children().eq(3).text(value['receivedqty']);
rowNew.children().eq(4).html('<input type="text" id="inspdate"/>');
rowNew.children().eq(5).html('<input type="text" id="accqty" onkeypress="return isNumber(event)"/>');
rowNew.children().eq(6).html('<input type="text" id="rejqty" class="reject"/>');
rowNew.children().eq(7).html('<input type="text" id="rema"/>');
rowNew.appendTo($tbody);
i++;
});
}
}
Since I am new to this, Please someone help me to do.
Try something like this
HTML
<table id="searchResultTable" class="display">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="resultscontainer">
</tbody>
</table>
Script
searchResultTable = $("#searchResultTable").dataTable({
"lengthMenu": [20],
"order": [[1, "desc"]],
"ordering": false,
"bFilter": false
});
searchResultTable.on('click', 'tr', DataTableRowClickEventHandler);
searchResultTable.fnClearTable();
for(i=0; i<response.length; i++){
....get values for Col1, Col2, Col3, Col4....
searchResultTable.fnAddData([Col1, Col2, Col3, Col4]);
}
Try below mentioned link for more documentation and examples,
https://datatables.net/examples/ajax/simple.html
I've got two tables (table1,table2) that are structurally the same, but fed from different sources. Both tables share the class 'display' which I use to initialise the plugin for both tables. This works great for the most part, however the column filters select menu for table2 is duplicated on table1.
I've tried to fix this by using 'this' keyword to indicate a particular instance of the toolbar each of the filters need applying to, but not had much success.
The code that works is:
HTML:
<table id="table1" class="display table-striped table-borded table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Report Name</th>
<th>Year</th>
<th>Montly Snapshot</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date of Last Refresh --var from warehouse-- </th>
</tr>
</tfoot>
</table>
<table id="table2" class="display table-striped table-borded table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Report Name</th>
<th>Year</th>
<th>Montly Snapshot</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date of Last Refresh --var from warehouse-- </th>
</tr>
</tfoot>
</table>
JS:
//initialise data tables plugin and apply custom settings.
var reportstable = $('table.display').DataTable({
"sDom": '<"toolbar">Bfrtlp',
"searchCols": [
null, {
'sSearch': 'Current'
}
],
language: {
search: "_INPUT_",
searchPlaceholder: "Search for a Report..."
},
// create select form controls
initComplete: function() {
this.api().columns([1, 2]).every(function() {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($('.toolbar'))
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
if ($('#info').css('display') == 'block') {
$("#reports_wrapper").css('display', 'none');
}
// add bootstrap classes and placeholder property to form controls to add style
$('.toolbar select').addClass('selectpicker');
$('.dt-button').addClass('btn btn-danger').removeClass('dt-button');
$('.toolbar select').attr('id', 'year');
$('#year').prop('title', 'Financial Year');
$("#year option:contains('Current')").remove();
$('.toolbar select:nth-of-type(2)').attr('id', 'month');
$('#month').prop('title', 'Monthy Snapshot');
$("#month option:contains('undefined')").remove();
});
});
},
// create clear filter button
buttons: [
{
text: 'Clear Filters',
action: function(e, dt, node, config) {
$('select').val('').selectpicker('refresh');
// set Current Year as default filter
reportstable
.search('')
.columns([1]).search('Current')
.columns([2]).search('')
.draw();
}
}
],
//hide specified columns
"columnDefs": [
{
"targets": [1],
"visible": false,
"searchable": true
}, {
"targets": [2],
"visible": false,
"searchable": true
}
]
});
I've updates your jsfiddle and created a new jsfiddle. It's now appending 2 select menus in both tables's wrapper div. I've found why it's appending 4 select menus instead of 2 on the table1's wrapper div. It's because of this code: .appendTo($('.toolbar')). When initComplete callback function is called for table1 there is only one div with class=toolbar, and when the initComplete callback function is called for table2 there is two div with class=toolbar, one in table1's wrapper div and one in table2's wrapper div. that's why on table2's initComplete callback function it append select menus to all divs with class=toolbar. We should rather append to the current table wrapper's div with class=toolbar.
I am trying to use datatables jQuery plugin, but having trouble and I can't figure out why is that happening.
I got an action column on my table:
table = $('#' + tableId).DataTable({
processing: true,
serverSide: true,
ajax: dataUrl,
deferRender: true,
esponsive: true,
pageLength: 15,
pagingType: "full_numbers",
stateSave: true,
filter: true,
language: {
paginate: {
next: " ",
previous: " ",
first: "First",
last: "Last"
}
}
$(document).on('click', ".details-control2", function () {
var tr = $(this).parent().parent(); // <-- finds the correct tr
var row = table.row(tr);
console.log(row); // <-- undefined, why??? 'table' is recognized correctly
}
Update - Table's HTML:
<tbody>
<tr id="row_0" role="row" class="odd">
<td class="sorting_1"></td>
<td><input type="image" src="/images/plus.png" class="details-control2"> </td>
<td>rasplap.dll</td>
<td></td>
<td>WIN7X86</td>
<td>DLL</td>
<td>4/4/2015 3:45:45 PM</td>
<td>4/4/2015 5:38:32 PM</td>
<td>0</td>
</tr>
</tbody>
Any suggestions? Please tell me if any info is missing.
try
$(this).parentNode.parentNode;
This is discussed in datatable forum: http://datatables.net/forums/discussion/11836/getting-data-on-click
I hope this helps:
$(document).on('click', ".details-control2", function () {
var row = $(this).closest('tr'),
data = table._(row),
id = data[0].id;
//do something with your id
//Get the position of the current data from the node
var aPos = table.fnGetPosition(id);//you many need to use ('#' + id)
// Get the data array for this row
var aData = table.fnGetData(id[0]);//you many need to use ('#' + id[0])
});
I am trying to sort a table - so when a user clicks on the table heading, it will sort in ascending/descending order. I've got it to the point where I can sort the table based on the column value. However, I have groupings of table rows (two rows per table body), and I want to sort the columns based on the values in the columns of the first row of each table body, but when it reorders the table, it want it to reorder the table bodies, not the table rows.
<table width="100%" id="my-tasks" class="gen-table">
<thead>
<tr>
<th class="sortable"><p>Name</p></th>
<th class="sortable"><p>Project</p></th>
<th class="sortable"><p>Priority</p></th>
<th class="sortable"><p>%</p></th>
</tr>
</thead>
<tbody>
<tr class="sortable-row" id="44">
<td><p>dfgdf</p></td><td><p>Test</p></td>
<td><p>1</p></td><td><p>0</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>asdfds</p></td>
</tr>
</tbody>
<tbody>
<tr class="sortable-row" id="43">
<td><p>a</p></td>
<td><p>Test</p></td>
<td><p>1</p></td>
<td><p>11</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>asdf</p></td>
</tr>
</tbody>
<tbody>
<tr class="sortable-row" id="40">
<td><p>Filter Tasks</p></td>
<td><p>Propel</p></td>
<td><p>10</p></td>
<td><p>10</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>Add a button to filter tasks.</p></td>
</tr>
</tbody>
</table>
With the following javascript:
jQuery(document).ready(function () {
jQuery('thead th').each(function(column) {
jQuery(this).addClass('sortable').click(function() {
var findSortKey = function($cell) {
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
var sortDirection = jQuery(this).is('.sorted-asc') ? -1 : 1;
var $rows = jQuery(this).parent().parent().parent().find('.sortable-row').get();
jQuery.each($rows, function(index, row) {
row.sortKey = findSortKey(jQuery(row).children('td').eq(column));
});
$rows.sort(function(a, b) {
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
jQuery.each($rows, function(index, row) {
jQuery('#propel-my-tasks').append(row);
row.sortKey = null;
});
jQuery('th').removeClass('sorted-asc sorted-desc');
var $sortHead = jQuery('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
jQuery('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
});
});
});
You need to sort the tbody elements, not the row elements. You said that yourself in your description of the problem, but your code actually sorts rows, not tbodies.
A secondary problem is that your sort treats everything as a string, which breaks when sorting 1-digit numeric strings ("2") against two-digit strings ("10").
To fix, replace this:
var $rows = jQuery(this).parent().parent().parent()
.find('.sortable-row').get();
jQuery.each($rows, function(index, row) {
row.sortKey = findSortKey(jQuery(row).children('td').eq(column));
});
with this:
var $tbodies = jQuery(this).parent().parent().parent()
.find('.sortable-row').parent().get();
jQuery.each($tbodies, function(index, tbody) {
var x = findSortKey(jQuery(tbody).find('tr > td').eq(column));
var z = ~~(x); // if integer, z == x
tbody.sortKey = (z == x) ? z : x;
});
And then replace $rows with $tbodies throughout your script, and row with tbody.
Example:
http://jsbin.com/oxuva5
I highly recommend the jQuery plugin http://tablesorter.com/ instead of rolling your own.
It's fully featured and well supported.