get the data from the datatable on click - javascript

How to get the data object on click the cell.I have created the table and used datatable.I want to get the geography and customer type from the cell click I have tried as
$('#table tbody').on( 'click','td', function () {
//alert ('clicked');
//var data1 = table.row().data();
var data1 = table.row( $(this).parents('tr') ).data();
console.log(data1);
alert( data1[0] +"'s Customer type: "+ data1[ 2 ] );
} );
my table id is table and I got the response as below in console for console.log(data1);
{Geography: "APAC", Current: "0", CustomerType: "AMRevenue", DSO: "0", OverDue: "0"}
getting undefined for data1[0] how to get the geo and customer type

First you need to assign variable as table for datatable initialize & in datatable there is one initComplete method so from this method to get table id by dynamically and then use click method functionality inside initComplete method as below code. So tr of tbody & get value table.row(this).data() method.
I hope below snippet will help you a lot.
$(document).ready(function() {
var table = $('#table').DataTable({
columns: [
{ title: "Geography" },
{ title: "Current" },
{ title: "Customer Type" },
{ title: "DSO" },
{ title: "OverDue" }
],
initComplete: function(settings, json){
$('#'+settings.sTableId+' tbody tr').on('click', function(){
var data = table.row(this).data();
console.clear();
console.log('Geography=> '+data[0]);
console.log('Customer Type=> '+data[2]);
});
}
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<table id="table" class="display" style="width:100%; text-align: center;">
<tbody>
<tr>
<td>APAC</td>
<td>0</td>
<td>AMRevenue</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>CAAP</td>
<td>1</td>
<td>CARevenue</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>JAPA</td>
<td>1</td>
<td>JARevenue</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>

If you add a click event on td and click on each td, you can be able to get the value of that td's data by using $(this).text();. Have a look at the snippet below and after running the snippet click on the td and see the value.
$("#myTable tbody td").click(function () {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table class="table" id="myTable">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Burl</td>
</tr>
</tbody>
</table>
Update: If you click on a specific row and want to get the entire row's data you can simply follow this way:
$("#myTable tbody td").click(function () {
var row = $(this).closest("tr"); // Find the row
var cell1 = row.find("td:nth-child(1)").text(); // Find the first cell's data
var cell2 = row.find("td:nth-child(2)").text(); // Find the second cell's data
console.log(cell1 + " " + cell2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Burl</td>
</tr>
</tbody>
</table>

I think you miss some little thing, just check my code:
<table id="table" class="display" width="100%"></table>
In file javascript:
var dataSet = [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
]
];
$(document).ready(function () {
$("#table").DataTable({
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
]
});
var table = $("#table").DataTable();
$("#table tbody").on("click", "tr", function () {
var data = table.row().data();
console.log('data', data);
alert(data[0] + "'s salary is: " + data[5]);
});
});
You will get your data in row

Related

No data available in first line of data table

After getting the data from firebase, the first line in the datatable is showing no data available.
How should I correct this?
I know I'm only using one data set but I try with 10 data it's still showing that there is no data available in the first line.
I tried everything I know but nothing works.
Output
My js code
$(document).ready(function() {
$('#user_data').DataTable({
dom: 'Bfrtip',
colums: [
{ title: "USN" }, { title: "Email" }, { title: "Name" }, { title: "Password" }
],
targets: -1,
className: 'dt-body-right',
hover: 1,
});
});
var rootRef = firebase.database().ref().child("StudentID");
rootRef.on("child_added", snap => {
USN = snap.child("UserUSN").val();
Email = snap.child("Useremail").val();
Name = snap.child("Username").val();
Password = snap.child("Userpassword").val();
$("#table-body-pengguna").append("<tr><td>" + USN + "</td><td>" + Email +
"</td><td>" + Name + "</td><td>" + Password + "</td></tr>");
})
My html code
<body>
<table id="user_data" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>USN</th>
<th>Email</th>
<th>Name</th>
<th>Password</th>
</tr>
</thead>
<tbody id="table-body-pengguna">
</tbody>
</table>
$(document).ready(function() {
$('#example').DataTable({
"pageLength": 1,
ajax: "https://raw.githubusercontent.com/bmehler/employees/main/personal",
"columns": [{
"data": "id"
},
{
"data": "name"
},
{
"data": "job"
},
]
});
});
<link href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Job</th>
</tr>
</tfoot>
</table>
Just try this small example.

How can i get data-id value(id) store in Array using JavaScript?

how can i get id number(data-id) using JavaScript. I'm using sortable.min.js for drag & drop. i want to get the td ID(data-id) which is inside of #drop table and store it into a array(sort)?
table.html
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Story</th>
</tr>
</thead>
<tbody id="drop" class="sortables">
<tr>
<td data-id="67">67</td>
<td>this is test post for (news2)d</td>
</tr>
<tr>
<td data-id="59">59</td>
<td>how to use custom fonts in dja</td>
</tr>
<tr>
<td data-id="51">51</td>
<td>how can i merge two forms fiel</td>
</tr>
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Story</th>
</tr>
</thead>
<tbody id="drag" class="sortables">
</tbody>
</table>
script.js
new Sortable(drag, {
group: '.sortables',
animation: 150,
});
new Sortable(drop, {
group: '.sortables',
animation: 150,
onChange: function (e, tr) {
sort = [];
$("#drog").children().each(function () {
sort.push({ 'id': $(this).data('id') })
});
console.log(sort)
},
});
As pointed out, you have a Typo in your Selector:
$("#drog")
Should be:
$("#drop")
You can also consider the following.
new Sortable(drag, {
group: '.sortables',
animation: 150,
});
new Sortable(drop, {
group: '.sortables',
animation: 150,
onChange: function (e, tr) {
var sort = [];
$("#drop > tbody > tr").each(function (i, row) {
sort.push({ 'id': $("td:first", row).data('id') });
});
console.log(sort);
},
});
Your previous code was targeting the children of #drop, which are <TR> elements and do not have the Data attribute.
The new code targets the 1st <TD> element of each row. This element has the Data attribute.

Get attribute value from datatables row for every record

I am working with datatables and I want to edit and delete data table records
When I do console.log(row) following output I get:
["user1", "Edit"]
(index):274 (2) ["user2", "Edit"]
(index):274 (2) ["user3", "Edit"]
(index):274 (2) ["user4", "Edit"]
(index):274 (2) ["user5", "Edit"]
What I want is to get data-id from render: function (data, type, row) which I have used in datatable script and when click on edit button I want to get specific id in alert but I am unable to extract data-id.
My jQuery code:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#catgeory_list').DataTable({
processing: true,
language: {
emptyTable: 'no result found.'
},
columnDefs: [{
visible: true,
targets: 0,
render: function (data, type, full, meta) {
return data;
}
}, {
visible: true,
targets: 1,
render: function (data, type, row) {
console.log(row);
return '<button id="editBtn" class="btn btn-wrang btn-flat edit" name="editBtn" type="button">Edit</button>' + ' <button id="deleteBtn" class="btn btn-danger btn-flat delete" name="deleteBtn" type="button" >Delete</button>';
}
}
],
});
In order to get any source object/array property/item for the row being clicked, you don't need anything more than simple row().data() API method invoked against DataTable row (selected by the closest to the clicked button <tr> node):
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
Here, dataTable is a variable, you assign your DataTable to.
Full-blown DEMO you might find below.
Also, considering your ultimate goal, you might find of use my answer over here, which provides complete working demo of editable DataTable. So, if you find that helpful, upvotes are appreciated ;)
//src data
const srcData = [
{id: 1, item: 'apple'},
{id: 2, item: 'banana'},
{id: 3, item: 'tomato'}
];
//datatables init
const dataTable = $('table').DataTable({
dom: 't',
data: srcData,
columns: [{data: 'item', title: 'Item Name', render: data => data+'<button>Show Id</button>'}]
});
//click handler
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
td button {float: right}
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table></table></body></html>
You can wrap data or row parameter from callback function with jQuery $() to get any element/node attributes or DOM manipuation. Refer also toJQuery() for dealing with Datatables API instances.
Render
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
createdRow
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
Click Event
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
Working Live Demo:
$(document).ready( function () {
var table = $('#example').DataTable({
columnDefs: [
{
targets: 1,
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
},
],
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
});
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css"
rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Edit</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$4,800</td>
</tr>
</tbody>
</table>

DataTables warning: table id=example - Requested unknown parameter '1' for row 1, column 1

Getting error "DataTables warning: table id=example - Requested unknown parameter '1' for row 1, column 1. For more information about this error, please see http://datatables.net/tn/4" while loading the data from ajax api call the json received from the back end is as below
[{"CustomerName":"Dinesh","product":"23234","perticulars":"wrwer","AddressOfCustomer":"wrew`","ContactNumbers":"jhkjhb"}, {"CustomerName":"dd","product":"dfsdfs","perticulars":"fsdfs","AddressOfCustomer":"sdfsdf","ContactNumbers":"fsfsf"}, {"CustomerName":"Pratik","product":"toothbrush","perticulars":"6 inch","AddressOfCustomer":"shreedhama white rose","ContactNumbers":"9949634396"}]
Snippet of HTML div tag for which table data is being populated is as below.
<table id="example" class="display" align="center" vertical-align="middle"; cellspacing="0" width="100%">
<thead>
<tr>
<th>Customer Name</th>
<th>Product</th>
<th>Perticulars</th>
<th>Address of customer.</th>
<th>Contact number</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Customer Name</th>
<th>Product</th>
<th>Perticulars</th>
<th>Address of customer.</th>
<th>Contact number</th>
</tr>
</tfoot>
</table>
Below is the ajax call I am doing and in success function trying to populate data from the json
$.ajax({
url:'AddQuotation',
type:'get',
success:function(data){
alert(data);
var resultTable = $('#example').DataTable({
"columns": [
{ data: "CustomerName" },
{ data: "product" },
{ data: "perticulars" },
{ data: "AddressOfCustomer" },
{ data: "ContactNumbers" }
],
"destroy": true,
"dom": 'lrtip'
} );
resultTable.rows.add(data1).draw();
dataSet = data;
},
error:function(){
alert('error');
}
});
You need to have data object that includes your array of objects.
{"data": [{"CustomerName":"Dinesh","product":"23234","perticulars":"wrwer","AddressOfCustomer":"wrew`","ContactNumbers":"jhkjhb"}, {"CustomerName":"dd","product":"dfsdfs","perticulars":"fsdfs","AddressOfCustomer":"sdfsdf","ContactNumbers":"fsfsf"}, {"CustomerName":"Pratik","product":"toothbrush","perticulars":"6 inch","AddressOfCustomer":"shreedhama white rose","ContactNumbers":"9949634396"}]}
A working DEMO.
In my case I just changed the following in my code and the error
DataTables warning: table id=bootstrap-data-table2 - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
was gone:
From:
<tbody>
#foreach (var item in Model.HRMS_Tbl_ExpenseClaimModelList)
{
<tr>
#if (item.Approved == "1")
{
<td>#item.Date</td>
<td>#item.Date</td>
<td>#item.Type</td>
<td>#item.Amount</td>
}
</tr>
}
</tbody>
To:
<tbody>
#foreach (var item in Model.HRMS_Tbl_ExpenseClaimModelList)
{
if (item.Approved == "1")
{
<tr>
<td>#item.Date</td>
<td>#item.Date</td>
<td>#item.Type</td>
<td>#item.Amount</td>
</tr>
}
}
</tbody>

Filter columns with DataTables Buttons based on attribute value

I have a custom button above my DataTables. When pressed I want it to filter the first column on a attribute value since this column cells only contain images (flags of countries/regions).
My table looks like this:
<table id="example">
<thead>
<tr>
<th>Region</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td data-order="United States"><img src="img/region_usa.png"></td>
<td>George</td>
<td>Washington</td>
</tr>
<tr>
<td data-order="Europe"><img src="img/region_eur.png"></td>
<td>Michael</td>
<td>Ferguson</td>
</tr>
<tr>
<td data-order="Japan"><img src="img/region_jap.png"></td>
<td>Yuka</td>
<td>Sakamari</td>
</tr>
</tbody>
</table>
This is my initilization:
$('#example').DataTable({
buttons: [
{
text: "Filter: USA",
action: function(e, dt, node, config){
dt.column(0).search("United States").draw();
}
}
]
})
However this doesn't do anything unfortunately. What am I doing wrong?
I used Buttons collection, Buttons.action and column.search() as reference.
Remember import datatTables.buttons.js
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.1/js/dataTables.buttons.min.js"></script>
change your attr data-order by data-search (check HTML5 attr https://datatables.net/examples/advanced_init/html5-data-attributes.html)
...
<td data-search="United States"><img src="img/region_usa.png"></td>
...
and indicate the dom.
$(document).ready(function() {
$('#example').DataTable({
dom: 'Bfrtip',
buttons: [
{
text: "Filter: United States",
action: function(e, dt, node, config){
dt.column(0).search("United States").draw();
}
}
]
})
});
Result : https://jsfiddle.net/cmedina/7kfmyw6x/63/

Categories