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])
});
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
On my view page I have a table (from a partial view) and a form. I am using ajax to submit the form to my webapi controller.
On success I would like to add what was entered in the textbox to the first column, and links to Edit and Delete in the second column of a new row.
As of right now I am only working on the Edit link.
Here is my partial view table:
<table id="Table" class="table table-bordered">
<thead>
<tr>
<th class="col-md-6">
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td class="col-md-6">
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td class="col-md-6">
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
Here is my form jquery.ajax:
var table = $("#Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1] },
{ "bSearchable": false, "aTargets": [1] }
]
});
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: infoGetUrl,
method: "post",
data: $("form").serialize()
}).success(function (data) {
var editLink = document.createElement('a');
editLink.href = "/controllerName/Edit/" + data.id;
editLink.text = "Edit";
table.row.add([
$("#Textbox").val(),
editLink
]).draw();
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("error");
});
});
The problem is that when this renders I get this:
It is not clickable and renders like this:
<tr class="even" role="row">
<td class="sorting_1">John.Doe</td>
<td>http://localhost:61888/controllerName/Edit/15</td>
</tr>
As you can see, it is not rendered in an a tag, and I don't need the http://localhost:61888 part of the link.
How can I resolve this?
try creating link as:
var link = <a href='/controllerName/Edit/' + data.id>EDIT</a>
With pur JS:
var link = document.createElement('a');
link.textContent = 'Edit';
link.href = "/controllerName/Edit/" + data.id;
you just need to place this inside your td.
If you want to remove 'http://localhost:61888' you can just use replace to change your localhost by un empty string. Or split your string and just keep the second part
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');
}));
I found out how to delete a row with this jQuery code. While clicking on a td with the class delete and a garbage icon.
HTML
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
JAVASCRIPT
$('#foo tbody').on( 'click', 'tr .delete', function () {
$(this).closest('tr').fadeOut("slow", function(){
$(this).remove();
})
} );
But I did not find anything about duplicating rows. I just want to click on a td with another icon in it and the row is duplicated below.
To duplicate a row, you'll need to copy all of its data into an array, then call row.add() to insert this data as a new row.
Something like:
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td class="copy">IMAGE src here</td>
<td><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
$('#foo tbody').on( 'click', 'tr .copy', function () {
var row_data = [];
$(this).closest('tr').find('td').each(function() {
row_data.push($(this).text());
});
// you'll need a reference to your DataTable here
table.row.add(row_data).draw();
});
To get a reference to your DataTable, assign the result of the DataTable() method to a var.
$(document).ready(function() {
var table = $('#foo).DataTable( { "paging": false, "info": false });
// set up your event handlers, etc.
});
If you append a row with jQuery instead of DataTables method like row.add(), you'll lose the row when you sort or page the table.
Here's the jQuery that adds a row duplicate right underneath it, where DataTables is concerned. It has a caveat that this method may not retain any sorting or filtering set by the user.
$('#formtable tbody').on( 'click', 'button.btn-success', function () {
//destroy instance of DataTables
table.destroy(false);
//script assumes button is clicked on the line that needs to be duplicated
var btn = this;
//copy and insert row right below the original
var line = $(btn).parents('tr');
line.after(line.clone());
//since clone retains only input field values, but not dropdown selections,
//each dropdown value must be assigned individually
line.next().find("select.shape").val(line.find("select.shape").val());
line.next().find("select.material").val(line.find("select.material").val());
line.next().find("select.supplied").val(line.find("select.supplied").val());
//re-creating DataTables instance
//notice that "table" has no "var" in front - that's because it is pre-defined.
table = $('#formtable').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": "_all"
} ],
"paging": false,
"info": false,
"ordering": true,
"searching": false,
"rowReorder": true
});
//"Index Column" values re-calculation
table.column(0).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
});
});
Hope this helps.
Try this:
HTML
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td class="duplicate"><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
</table>
SCRIPT
$('#foo tbody').on( 'click', 'tr .delete', function () {
$(this).closest('tr').fadeOut("slow", function(){
$(this).remove();
})
} );
$('#foo tbody').on( 'click', 'tr .duplicate', function () {
var myTr = $(this).closest('tr');
var clone = myTr.clone();
myTr.after(clone);
} );
This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
$('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
You can also use the DataTables plugins api which allows you to create custom renderers.
Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
**I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );