How to use "formatter" dynamically in jqGrid.Is it possible? - javascript

Is there a way to dynamically use the "formatter" in jqGrid?I want to make use of formatTitle function from the code dynamically, Here is my code:
HTML
<table id="list47"><tr><td></td></tr></table>
<div id="plist47"></div>
Javascript:
var md=[{ "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
{ "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
{ "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }]
var he=["id","Name","PackageCode"];
var c=[];
for(var i=0;i<he.length;i++){
c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"}');
}
var colmodel="["+c+"]"
//var colmodel= [{name:'id', index:'id', width:55},
// {name:'Name', index:'Name' },
// {name:'PackageCode', index:'PackageCode'}]
// c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+'"formatter":'+formatTitle+'}');
jQuery("#list47").jqGrid({
//data: md,
datatype: "local",
height: 150,
rowNum: 10,
colNames: he,
colModel: jQuery.parseJSON(colmodel),
rowList: [10,20,30],
pager: "#plist47",
viewrecords: true,
caption: "json data grid"
});
for(var i=0;i<md.length;i++){
jQuery("#list47").addRowData(i+1,md[i]);
}
function formatTitle(cellValue, options, rowObject) {
return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";
//return cellValue.substring(0, 50) + "...";
};

You have to put the formatter in a string as follows
for(var i=0;i<he.length;i++){
c.push('{"name":"'+he[i]+'","index":"'+he[i]+'"'+',"formatter":"formatTitle"'+'}');
}
Then you defind the formatter before the jqGrid code as follows
$.fn.fmatter.formatTitle = function (cellValue, options, rowObject) {
return "<a href='" + rowObject.Link + "'>" + cellValue.substring(0, 45) + "..." + "</a>";
};
Because it is wrapped in a string(formatter: "formatTitle") you cant use your former signature for the formatter which was
function formatTitle(cellValue, options, rowObject) This can be used if formatter: formatTitle which is not possible to construct dynamically
Here is a jsfiddle solution to your problem

Related

How to make a column value copyable and not editable in Ag-grid - JavaScript

I have a javascript grid (ag grid)
var columnDefinitions = [
{
headerName: 'Item Number',
field: 'ItemNumber',
width: 140,
editable: editable && status !== 'Open',
cellClass: 'ag-autocomplete',
cellEditor:Grids.CellEditors.ItemEditor({
updateCallback: function (rowData, selectedItem) {
rowData.ItemId = selectedItem.Id;
rowData.Description = selectedItem.Description;
},
getInitialFilters: function () {
return [
{ Identifier: "VId", Values: [$("#Id").val()] }
];
},
searchDefinition: 'InvItems.json',
autocompleteSearchDefinition: 'InvDetail.json'
})
},
.....
{
headerName: 'Tracking Number',
field: 'TrackingNumber',
width: 120,
cellRenderer: function (params) {
if (params.data.TrackingNumber != null) {
var url;
if (params.data.Carrier == 'UPS') {
url = 'https://wwwapps.ups.com/tracking/tracking.cgi?tracknum=';
}
if (params.data.Carrier == 'USPS') {
url = 'https://tools.usps.com/go/TrackConfirmAction.action?tLabels=';
}
return "<a target='_blank' href='" + url
+ params.value
+ "'>" + params.value + "</a>";
}
else {
return '';
}
}
},
I want to make the column "TrackingNumber" copyable. I don't want to make it editable. anything I try that make it like a textbox and I can copy the value I can edit it too that I don't want that.
Add enableCellTextSelection: true to your grid options. Docs here

How to get value textbox in datatable column jquery and push to a variable?

I want to get a value of 53.54.57 but somehow I always get the value of 53.53.53 not as expected. anyone can help me?
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{ data: 'harga' },
{ data: 'qty' },
{ data: 'total' },
{ data: 'remove' },
{ data: 'untung' },
]
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
$("#" + $(data.remove).attr("id")).val();
I use this function to retrieve data from the datatable, but the line can only be the same value. always a value of 53, how to get the value of a line in the column called 'remove'
Is my looping wrong? or is there another way to get that value?
Like #charlietfl said, it seems you're duplicating the element ids.
If I understood you correctly, and the id of your input(type number) is the value, then you only need to change one line:
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id;
//change this line
//master_barang_id = $("#" + $(data.remove).attr("id")).val(); //the method I use to retrieve data
//for this one
master_barang_id = $("#" + data.remove).val();
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
This is a working example:
var jsonData = [{ "linenum": 1, "nama": "lampu economat 3w LED", "harga": 20000, "qty": 1, "total": 20000, "remove": 53, "untung": "X" }, { "linenum": 2, "nama": "lampu economat 5w LED", "harga": 25000, "qty": 1, "total": 25000, "remove": 54, "untung": "X" }, { "linenum": 3, "nama": "lampu economat 9w LED", "harga": 30000, "qty": 1, "total": 30000, "remove": 57, "untung": "X" }];
$("#btnGetData").click(function() {
$("#table-main").DataTable().rows().every(function(){
var data = this.data();
var master_id = $("#" + $(data.remove).attr("id")).val();
//53,54,57 is index column name = "remove"
var master_barang_id = $("#" + data.remove).val(); //the method I use to retrieve data
alert(master_barang_id); //it should alert 53,54,57 BUT alerts only appear 53,53.53
});
});
var oTable = $('#table-main').DataTable({
data: jsonData,
columns: [
{ data: 'linenum' },
{ data: 'nama' },
{
data: 'harga',
"render": function (data, type, row, meta) {
return '<input type="text" value=' + data + ' />';
}
},
{
data: 'qty',
"render": function (data, type, row, meta) {
return '<input type="number" value=' + data + ' />';
}
},
{ data: 'total' },
{
data: 'remove',
"render": function (data, type, row, meta) {
return '<input type="number" id="' + data + '" value=' + data + ' />';
}
},
{ data: 'untung' },
]
});
input {
text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<div class="data-table-container">
<table id="table-main" class="table cell-border order-column stripe">
<thead>
<tr>
<th>linenum</th>
<th>nama</th>
<th>harga</th>
<th>qty</th>
<th>total</th>
<th>remove</th>
<th>untung</th>
</tr>
</thead>
</table>
</div>
<br>
<input type="button" id="btnGetData" value="GET DATA" />

jQuery Datatable make each cell a link

I have four entities, let's say A,B,C,D which are interconnected (B depends on A, C depends on B, D depends on C). I want to display all the information in one table that can be easily searched and filtered.
So I created a view model of form:
public class MyViewModel {
public Aname {get; set;}
public Alink {get; set;}
public Bname {get; set;}
public Blink {get; set;}
public Cname {get; set;}
public Dname {get; set;}
public Dlink {get; set;}
}
I want the table to have four columns to display the name of each entity and each data in a cell to be a hyperlink that leads to the details page of the selected entity (except entity C).
Here is the javascript
$('#myDataTable').DataTable({
'bDestroy': true,
"bInfo": true,
"bProcessing": true,
"bDeferRender": true,
'iDisplayLength': 10,
'sPaginationType': 'full_numbers',
'sPageButtonActive': "paginate_active",
'sPageButtonStaticDisabled': "paginate_button",
'data': OptionsHandler.Data,
"columnDefs": [
{
"render": function (data, type, row) {
return "<a href=" + row[1] + "'>" + row[0] + "</a>";
},
},
]
});
But it complains that
Requested unknown parameter 0 for row 0. For more information about
this error, please see http://datatables.net/tn/4
Data is in Json format:
data = [
{"Aname":"PatriceBoyle",
"Alink":"/A/Details/00014",
"Bname":"Software Engineering",
"Blink":"/B/Details/2",
"Cname":"info",
"Dname":"Database Design",
"Dlink":"/D/Details/1"
}, etc.]
How can I say: return "<a href=" + link + "'>" + name + "</a>"; for each cell?
row[1] implies either an array index or object property name of '1' but you have neither.
You need something like:
return "<a href=" + row.Alink + "'>" + row.Aname + "</a>";
I stripped your code down to the minimum and got the same error until I changed you columndefs to columns instead:
columns: [
{ title: "Aname", data: "Aname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[0] + "</a>"; } },
{ title: "Alink", data: "Alink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[1] + "</a>"; } },
{ title: "Bname", data: "Bname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[2] + "</a>"; } },
{ title: "Blink", data: "Blink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[3] + "</a>"; } },
{ title: "Cname", data: "Cname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[4] + "</a>"; } },
{ title: "Dname", data: "Dname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[5] + "</a>"; } },
{ title: "Dlink", data: "Dlink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[6] + "</a>"; } }
]
I managed to do it combining the two answers:
columns: [
{ title: "Column A", data: "Aname", render: function (data, type, row) { return "<a href=" + row.Alink + "'>" + row.Aname + "</a>"; } },
{ title: "Column B", data: "Bname", render: function (data, type, row) { return "<a href=" + row.Blink + "'>" + row.Bname + "</a>"; } },
{ title: "Column C", data: "Cname", render: function (data, type, row) { return "<a href=" + row.Clink + "'>" + row.Cname + "</a>"; } },
{ title: "Column D", data: "Dname", render: function (data, type, row) { return "<a href=" + row.Dlink + "'>" + row.Dname + "</a>"; } },
]

Passing parameters through HTML in .cshtml file

I have this code in a .cshtml file:
var peopleList = $('#PeopleListTable').dataTable({
// not relevant
"fnRender": function (oObj) {
var documentiddata = oObj.aData[0];
var notesdata = (oObj.aData[2]);
//alert(notesdata);
if (notesdata != null) {
var image = "images/AR/Check-on.png";
// return '' + '<img src="' + image + '" />' + '';
return '<p><a onmouseout="return hideNotePopup();" onmouseover="return showNotePopup(notesdata, event);" href="javascript:void(0);" id="' + documentiddata + '">' + '<img src="' + image + '" />' + '</a></p>'
} else {
return ' ' + '<img src="images/AR/Check-off.png" />' + '';
}
}
},
{ "sName": "OfficerName", sType: "string", sWidth: "12%" },
{ "sName": "CreateDate", sType: "string", sWidth: "15%" },
{ "sName": "FinalizedDate", sType: "string", sWidth: "15%" },
{ "sName": "TransferDate", sType: "string", sWidth: "15%" },
{ "sName": "AgencyOri", sType: "string", sWidth: "10%" }
]
});
Then this code in JavaScript:
function showNotePopup(notesdata, e) {
$("#NoteDialog").dialog('close');
$("#NoteDialog").removeClass("ui-icon ui-icon-closethick");
$("#NoteDialog").dialog({
autoOpen: false,
modal: true,
resizable: false,
position: [e.pageX, e.pageY-190]
});
$("#NoteDialog").dialog('open');
document.getElementById("note").innerHTML = notesdata;
}
The goal of this code is to hover over the note image in a data table, then have a popup show the contents of the note. Where I have alert(notesdata), the note is shown properly. But when I hover over the image and examine the console, it says that notesdata isn't defined in the showNotePopup() call. I tried passing this and oObj as well, to no avail. How can I get notesdata from inside the cshtml to the javascript function?
Variable notesdata exists only on the context of function fnRender. The event onmouseover is executed on a different context so the variable is out of scope. You need to change
onmouseover="return showNotePopup(notesdata, event);"
by
onmouseover="return showNotePopup("' + notesdata + '", event);"

Change JQGrid Cell value on Button Click

I am using jqgrid in asp.net webforms. I have a column which name is Actions, in which I have button Add I want that when I click on add button, then cell value should be changed. Like I have button in this cell, when I click on add button, then it should change with text. Please, guide me. Code is given below which i am using.
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
 
jQuery("#jQGridDemo").jqGrid({
url: 'HttpHandlers/CustomersList.ashx',
datatype: "json",
colNames: ['Opted-In', 'Name', 'Email', 'Filter Matches', 'Customer Id','Actions'],
colModel: [
{ name: 'OptedIn', index: 'OptedIn', width: 40,align:'center', stype: 'text', formatter: OptedInValue },
{ name: 'CustomerName', index: 'CustomerName', width: 90, stype: 'text', sortable: true },
{ name: 'CustomerEmail', index: 'CustomerEmail', width: 110, stype: 'text', sortable: true },
{ name: 'FilterLetter', index: 'FilterLetter', width: 60 },
{ name: 'CustomerId', index: 'CustomerId', width: 60, hidden: true },
{ name: 'Actions', index: 'Actions',editable:true, width: 60,align:'center',formatter: ButtonValue }
],
width: 600,
height:300,
rowNum: 30,
mtype: 'GET',
loadonce: true,
rowList: [30, 60, 90],
pager: '#jQGridDemoPager',
sortname: 'OptedIn',
viewrecords: true,
sortorder: 'asc',
caption: "Customer List"
});
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var link = '';
if (filterLetter == " A") {
link = '<button type="button" onclick=addGridCustomer(' + rowObject.CustomerId +')>Add</button>';
} else {
link = '<div id="rowelder"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId +')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id,rowId) {
debugger
var rowData = $('#jQGridDemo').jqGrid('getRowData', rowId);
rowData.Actions = '12321';
$('#jQGridDemo').jqGrid('setRowData', rowId, rowData);
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
UpdateFiltersForCusRemove(id);
}
i work on this problem and found the solution here below is the problem of my solution.
function ButtonValue(cellvalue, options, rowObject) {
var filterLetter = rowObject.FilterLetter;
var Id = qs("id");
var link = '';
if (Id != 0) {
link = '<div id="addbutton"><button type="button" onclick=addGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Add</button></div>';
}
else {
link = '<div id="removecustomer"><button type="button" onclick=removeGridCustomer(' + rowObject.CustomerId + ',' + options.rowId + ')>Remove</button></div>';
}
return link;
}
function OptedInValue(cellvalue, options, rowObject) {
var optedIn = rowObject.OptedIn;
var link = '';
if (optedIn == true) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_success.png" />';
}
else if (optedIn == false) {
link = '<img title="View ' + rowObject.CustomerName + ' ' + '" src="/images/icn_alert_error.png" />';
}
return link;
};
function removeGridCustomer(id, rowId) {
debugger
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be removed ..');
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
//Update Filters in case of removal
UpdateFiltersForCusRemove(id);
}
function addGridCustomer(id, rowId) {
$('#<% = hdCustomer.ClientID %>').val($('#<% = hdCustomer.ClientID %>').val() + id + ',');
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div button').hide();
$("#jQGridDemo tr").eq(rowId).children().eq(5).find('div').append('to be added ..');
//Update Filters in case of removal
UpdateFiltersForCusAdd(id);
}
function UpdateFiltersForCusAdd(a) {
var filterLtr = $("#lblF" + a).text().trim();
var count = 0;
count = parseInt($("#filterL" + filterLtr).text().trim()) - 1
$("#filterL" + filterLtr).text(count);
TotalCustomers(+1);
}

Categories