Add Links to data rows result on Datatables using ASP VB.Net - javascript

I am using DataTables for my ASP project, I would like to have the first column to contain links.
Here's my code:
$.ajax({
data: JSON.stringify(CardCode),
dataType: "json",
url: "/WebServices/Invoice/BusinessPartner.asmx/GetJsonPrevTrans",
type: "POST",
contentType: "application/json; charset=utf-8",
success:
function (ef1) {
console.log(CardCode);
console.log(JSON.parse(ef1.d))
console.log(ef1)
$("#bpPrevJSONTrans").val(ef1.d).trigger('change');
var parsed = JSON.parse(ef1.d);
var bpPrevDt = $('#bpPrevTransData').DataTable({
retrieve: true,
responsive: true,
"bJQueryUI": true,
"bProcessing" : true,
"aaData": parsed,
"aoColumns": [
{ "sTitle": "Test", "mData": "test" },
{ "sTitle" : "Document Number","mData": "DocNum" },
{ "sTitle" : "Description", "mData": "Dscription" },
{ "sTitle": "Amount", "mData": "DocTotal", "sType": "numeric" }
]
});
}
});
Thank you!

If you need the Test one to contain a link then change the aoColumns arrays 1st element to below line,
{ "sTitle": "Test",
"mData": "test",
"fnRender":function(obj, type){
return "<a href='Your link goes here' >Click here</a>";
}
}

Instead of putting a link button in row details for me to do my function such as editing, I just used the fnRowCallBack function of the datatable. See code below:
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
// Bind click event
$(nRow).click(function () {
$('#viewInvoiceEntry').modal('show');
//Append Information on Modal:
$('#viewInvRefNum').val(aData.DocNum).attr("readonly", "readonly");
$('#viewInvDesc').val(aData.Dscription).attr("readonly", "readonly");
$('#viewInvAmnt').val(aData.DocTotal).attr("readonly", "readonly");
$('#viewInvDocDate').val(aData.DocDate).attr("readonly", "readonly");
$('#viewInvSrvc').val(aData.ItemName).attr("readonly", "readonly");
$('#viewInvCompGrp').val(aData.GroupName).attr("readonly", "readonly");
$('#viewInvCompName').val(aData.CompName).attr("readonly", "readonly");
$('#viewInvRemarks').val(aData.Comments).attr("readonly", "readonly");
//alert('You clicked on ' + aData.DocNum + '\'s row');
});
return nRow;
}

Related

how to save table state even after changing table pages

I have a dataTable that displays data from a database. I'ts displayed in a bootstrap modal and there is an option in each row to delete the row.
Here's the jquery that gets the data from the database:
function cart_contents() {
$.ajax({
url: "cartContents.php",
type: "POST",
dataType: "JSON",
success: function(data){
var table = $('#cart-content').dataTable();
table.fnDestroy();
table.dataTable({
"aaData": data,
"scrollX": false,
"lengthChange": false,
"ordering": false,
"pageLength": 6,
"language": {
"info": "Number of items: _TOTAL_"
},
"searching": false,
"aoColumns": [
{"sTitle": "Product", "mData": "product"},
{"sTitle": "Price", "mData": "price"},
{"sTitle": "Qty.", "mData": "quantity"},
{
"sTitle": "Edit", "mData": "id", "render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="sample(' + mData + ')">Edit</button>';
}
},
{
"mData": "id", "render": function (mData, type, row, meta){
return "<span style='cursor: pointer' class='close' onclick='remove_product(this," + mData + ")'>x</span>";
}
}
]
})
}
}
Here's the remove_product:
function remove_product(these, id){
var i = these.parentNode.parentNode.rowIndex;
document.getElementById("cart-content").deleteRow(i);
$.ajax({
type: "POST",
url: "remove_product.php",
data: {product_id: id},
success: function(data){
alert(data);
}
})
}
Now, the data may or may not exceed a single page on the table since it is set to display 6 rows. Therefore, there is a chance that there may be pagination. Whenever the 'x' is clicked to remove the row, it removes it on the page, and successfully deletes it in the database.
However, when I scroll to the next page of the table and go back previously, the row that was deleted comes back. How would I go about deleting it permanently, since it no longer exists in the database? I need to do this without reloading the modal.

Is it possible to use Ajax success result to populate jQuery DataTable

I would like to declare my jQuery datatable without initially populating it and later when calling Ajax functions, I would like to take the results and use that as the data source for my data table, right now I am making multiple Ajax calls for the same purpose and I would like to eliminate this if possible.
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
tbl = $("#UnorderedDetail")
.DataTable({
"destroy": true,
"searching": false,
"ordering": false,
"lengthChange": false,
"pagingType": "full_numbers",
"paging": true,
"lengthMenu": [10, 25, 50, 75, 100],
ajax: {
url: "/Receiving/GetUnorderedParts",
data: { "id": button.attr("data-ponumber") },
datasrc: ""
},
"columnDefs": [
{
targets: -1,
className: 'dt-body-center'
}
],
columns: [
{
data: "Description"
},
{
data: "VendorPartNumber"
},
{
data: "Quantity"
},
{
data: "CartID",
render: function(data) {
return "<button class='btn btn-danger js-delete' data-cart-id=" +
data +
">Delete</button>";
}
}
] //EOColumns
}); //EODataTable
} //EOSuccess
}); //EOInnerAjax
You can call a function to build the data table on success something like:
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
createTable(data);
}
});
and the function can take in the array of objects and create a data table:
function createTable(dataSet)
{
$('#example').DataTable({
data: dataSet,
"aoColumns": [{
"sTitle": "Description",
"mData": "Description"
}, {
"sTitle": "VendorPartNumber",
"mData": "VendorPartNumber"
}, {
"sTitle": "Quantity",
"mData": "Quantity"
}, {
"sTitle": "CartID",
"mData": "CartID",
"mRender": function(data) {
return "<button class='btn btn-danger js-delete' data-cart- id=" + data + ">Delete</button>";
}}]
});
}
Check out a working example . It takes in an array of objects and create a datatable.

JQuery Data table - Get a value of a different column from another column

How do I get the value of checklistclient_id column and insert into the onchange event at the last column?
When the change of checkbox value occurs, it brings the checklistclient_id to the togglecheck function.
function loadClientChecklist(url){
var rt_hash = decodeUrl(url);
var id = rt_hash[0].replace("id=", "");
$.ajax({
type: 'POST',
url: '../model/get_set_ajax2.php?req=21',
data: 'cid=' + id,
success: function (results) {
console.log(results);
$('#clchecklist_tab').DataTable({
"paging": false,
"searching": true,
"info": false,
"ordering": false,
"aaData": $.parseJSON(results),
"aoColumns": [
{"mData": "checklistclient_id", "visible": false},
{"mData": "description"},
{"mData": "is_checked", "mRender": function (data) {
return '<input type="checkbox" onchange="togglecheck('+ checklistclient_id +')" value='+data+'/>';
}
}
]
});
}
});
You should use row created callback Then you can set id to trs.
"createdRow": function ( row, data, index ) {
$(row).data("checklistclient_id", checklistclient_id );
}
Now, you know all id of tr. Lets say that your check box has class called cb
$("#clchecklist_tab" ).delegate( ".cb", "change", function() {
togglecheck($(this).closest("tr").data(checklistclient_id))
})"

click function is not working and if i comment $('#tablenew').dataTable( {}); its working but i want datatable too

Click function is not working and if I comment $('#tablenew').dataTable({}); out, it's working, but I want this to work with datatable
$( document ).ready(function() {
$('#tablenew').dataTable( {
'bProcessing': false,
'bServerSide': false,
'sort': 'position',
'sAjaxSource': 'springPaginationDataTables.web',
'aoColumns': [
{ "mData": "UserId" },
{ "mData": "UserName" },
{ "mData": "UserStatus" },
{ "mData": "UserType" },
{ "mData": "AddedBy" },
{ "mData": "AddedDateTime" },
{ "mData": "UpdatedBy" },
{ "mData": "UpdatedDateTime" },
]
});
$('#tablenew').find('tr').live('click', function(){
var row = $(this).find('td:first').text();
alert('You clicked ' + row);
/* $("#userId").value(row); */
var url = '/paymentGateway/userInfoPage/'+row;
$(location).attr('href',url);
});
});
DataTables redraws the table structure (rows/cells) often. The <tr>'s that are initially getting the click event bound to them are being removed when the table redraws. You'll need to bind the events using event delegation on the table, instead of on the table rows.
This should work:
$('#tablenew').on('click', 'tr', function(){ ... });

Undefined Object in DataTable

Have a datatable and using the drill down row. The top row populate data but the link to drill down to the additional row contains a undefined object and I'm stuck right there.
Any help would be so appreciated. oData.code (undefinded) / oData itself will return everything from the linq query but when I start using the oData.etc... the object becomes undefined. Even in the click event I've tried to access oData and drop it in the second TD row and it to is also undefined.
function fnFormatDetails(oTable, nTr)
{
var oData = oTable.fnGetData(nTr);
var sOut =
'<div>' +
'<table>' +
'<tr><td> '+oData.code+' </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'
'</table>' +
'</div>';
return sOut;
} //end fnFormatDetails function
$(document).ready(function ()
{
var anOpen = [];
var oTable = $('#VADataTable').dataTable(
{
"sDom": 'T<"clear">lfrtip',
"oTableTools":
{
"sSwfPath": "/swf/copy_csv_xls_pdf.swf"
}, //flash must be enabled
"iDisplayLength": 5, //defalut amount of rows shown on page
"bServerSide": false, //uses sever for filter curently turned off
"bFilter": false, //makes columns clickable to filter
"bProcessing": true,
"bserverSide":false,
"bJQueryUI": true, //enables user interface
"bSort": true, //sorting for columns
"bScrollInfinite": true, //using this takes away ddl of selection
"sAjaxSource": "Data/IndustryTable", //where ajax commands renders results
"sScrollY": "200px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
"fnRowCallback": function (nRow, aData)
{
if (aData[0] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "sName": "code", "sTitle": "Code" },
{ "sName": "code" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" },
{ "sName": "data" }
]
});
$('#VADataTable td.control').live('click', function ()
{
var nTr = this.parentNode;
var i = $.inArray(nTr, anOpen);
if (i === -1)
{
$('td').attr('+');
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
$('div', nDetailsRow).slideDown();
anOpen.push(nTr);
} //end if
else
{
$('td').attr('-');
$('div', $(nTr).next()[0]).slideUp(function ()
{
oTable.fnClose(nTr);
anOpen.splice(i, 1);
}); //ends slideUp
} //ends else
$('#new tr').after('<td> '+ typeof(oTable.code) +' </td>');
}); //ends click event
} //ends live event
)//ends ready function
I believe that just add the "mData" property in "aoColumns", that is the name of fields of database table, and in "fnRowCallback" you must replace "aData[0]" by "aData['code']" like the next example:
"fnRowCallback": function (nRow, aData)
{
if (aData['code'] == "")
{
$('td:eq(0)', nRow).html("+").addClass('control');
}
return nRow;
}, //ends fnRowCallback
"aoColumns":
[
{ "mData" : "code", "sName": "code", "sTitle": "Code" },
{ "mData" : "code", "sName": "code" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" },
{ "mData" : "data", "sName": "data" }
]

Categories

Resources