Passing parameters through HTML in .cshtml file - javascript

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);"

Related

Display Show More / Show Less option if text if more then 20 length

I try to add option in my Debatable column Description if text length is more then 20 character long display Show more option and collapse this column.
I try couple of option and one which work for me is something like this
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": "/Manager/Ticket/GetAll"
},
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type, row, meta) {
return type === 'display' && data.length > 20 ?
'<span title="' + data + '">' + data.substr(0, 17) + '...</span>' :
data;
}
}],
"columns": [
{
"data": "description",
"width": "10%",
//"render": function (data) {
// return 'Prikazi vise'
//}
},
{ "data": "shortDescription", "width": "10%" },
{ "data": "dateAndTime", "width": "10%" },
{ "data": "ticketType.name", "width": "10%" },
{ "data": "status", "width": "10%" },
{
"data": "applicationUser.name",
"width": "10%",
"render": function (data) {
return '<a id="' + data + '" class="text-info user-details" data-toggle="modal" data-target="#userDetails" href="' + data + '" target_blank>' + data + '</a>'
}
},
{
"data": "id",
"render": function (data) {
return `
<div class="text-center">
<a href="/Manager/Ticket/Details/${data}" class="btn btn-success text-white" style="cursor:pointer">
<i class="fas fa-info-circle">Detalji/Chat</i>
</a>
<a href="/Manager/Ticket/Upsert/${data}" class="btn btn-primary text-white" style="cursor:pointer">
<i class="fas fa-edit">Uredi</i>
</a>
</div>
`;
}, "width": "15%"
}
]
});
}
After I add columnsDef
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type, row, meta) {
return type === 'display' && data.length > 20 ?
'<span title="' + data + '">' + data.substr(0, 17) + '...</span>' :
data;
}
}],
This option works but only when User hover column it display text. I add ... and I want to create that this tree dots needs to be as <a> and should be clickable and when user click it needs to Show More and Show Less option.
I check couple of post here starting from this
REFERENCE 1
The problem here is that I am noob in jQuery and JavaScript and I have no idea how to implement this side.
This is how it look like right now
UPDATE
I found some solutions but doesn't work at all. I change my columnDef
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type) {
return type === 'display' && data.length > 20 ?
'<span id="outer" data-shrink="' + data.substr(0, 17) + '" title="' + data + '"></span><span id="show">...</span>' :
data;
}
}],
Here is my JavaScript
$(document).ready(function () {
$(".tblData").hide();
$(".showmore").on("click", function () {
var txt = $(".tblData").is(':visible') ? 'Vise' : 'Manje';
$(".showmore").text(txt);
$(this).next('.tblData').slideToggle(200);
});
});
I successfully add ... to be clickable, but when I click text is not showing.
UPDATE
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type) {
return type === 'display' && data.length > 20 ?
'<span id="outer" title="' + data + '">' + data.substr(0, 17) + '</span><span id="show">...</span>' :
data;
}
}],
$('#show').click(function () {
var text = $('#outer').attr('title');
$(this).text(text);
$('#show').after('<a id="less" onclick="someFunction()" href="#"> Show less</a>');
$('#outer').text('');
});
function someFunction() {
console.log('test');
$('#less').remove();
var txt = $('#outer').attr('data-shrink');
$('#show').text('');
$('#outer').text(txt);
$('#show').text('...');
}
var len = $('#outer').text();
if(len.length > 20) {
var txt = $('#outer').attr('data-shrink');
console.log(txt);
$('#outer').text(txt);
$('#show').text('...');
}
$('#show').click(function() {
var text = $('#outer').attr('title');
console.log('text', text.length);
$(this).text(text);
$('#show').after('<a id="less" onclick="someFunction()" href="#"> Show less</a>');
$('#outer').text('');
});
function someFunction() {
console.log('test');
$('#less').remove();
var txt = $('#outer').attr('data-shrink');
$('#show').text('');
$('#outer').text(txt);
$('#show').text('...');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="outer" data-shrink="Das ist ein" title="Das ist ein ganzer Text langer Text">Das ist ein sehr langer Text</span><span id="show"></span>
Just replace the html with your variables.

Using "later" variable in jQuery DataTables

My DataTables configuration is something like this:
(function ($) {
"use strict";
$(document).ready(function () {
$('#data-table-users').DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Users/GetUsersData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
.............................
{
"data": "Image",
"orderable": false,
"render": function (data, type, row, meta) {
var imgSrc;
if (data != null) {
imgSrc = '"data:image/jpeg;base64,' + atob(data) + '"';
}
else {
imgSrc = "/svg/" + "A" + ".svg";
}
return '<div><img class="small-img" src=' + imgSrc + '></div>';
}
},
{
"data": "UserName",
"render": function (data, type, row, meta) {
return '<div class="positioned"> <div class="editable" data-name="userName" contenteditable="true">'
+ data + '</div > <i class="fa fa-pencil pushright" aria-hidden="true"></i> </div>';
}
},
{
"data": "FirstName",
"render": function (data, type, row, meta) {
if (data == null)
data = "";
return '<div class="positioned"> <div class="editable" data-name="userName" contenteditable="true">'
+ data + '</div > <i class="fa fa-pencil pushright" aria-hidden="true"></i> </div>';
}
},
............................
],
"order": [[8, "desc"]]
});
});
})(jQuery);
For Image column I have in the Render function:
else {
imgSrc = "/svg/" + "A" + ".svg";
}
What I would like is instead of having imgSrc = "/svg/A.svg" is to construct it based on UserName column like so:
imgSrc = "/svg/" + userName[0].toUpperCase() + ".svg";
How can I do that without changing code on server side? It seems to me that DataTables is rendering UserName cell at a later time, so Image cell is already rendered. Can somehow a trigger be added when UserName is rendered to alter Image cell content?
I can change the values for all cells in Image column after the whole table gets rendered, but somehow I dislike that idea because it might look ugly. So, please, don't suggest that.
Just got it. I can access all data for the current row using row parameter.
So it's just:
imgSrc = "/svg/" + row['UserName'][0].toUpperCase() + ".svg";

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

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

Syntax error: Missing ; Before Statement

I am getting a syntax error on seemingly fine code, also the error does not make sense so that indicates there is some foul play. However, I cannot seem to pinpoint it. On the first line, "aoColumns: [" it states that there is a missing semi-colon before statement. Here is the code in question:
<script type="text/javascript">
"aoColumns": [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
]
"fnCreatedRow": function(nRow, aData, iDataIndex) {
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e){
$.get('/files?path='+ path).then(function(data){
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
});
e.preventDefault();
});
};
</script>
What you have looks like the content of an object initializer, but without the beginning and end of one. For instance, this is valid:
var object = {
"aoColumns": [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
],
"fnCreatedRow": function(nRow, aData, iDataIndex) {
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e){
$.get('/files?path='+ path).then(function(data){
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
});
e.preventDefault();
});
}
};
The changes are:
Adding the var object = { at the top
Removing the ; from the }; that used to be at the end, making it just }
Adding a }; to close the object
Adding a , after the closing ] on the aoColumns array
var obj = {
"key": value
};
Where are your curly braces? You're just trying to define object keys without placing them on an object, so that is why you're getting the syntax error.
var my_object = {
"aoColumns": [
// code here
],
"fnCreatedRow": function(nRow, aData, iDataIndex) {
// function definition here
}
};
What you have there is not valid JavaScript syntax.
Assuming you want to assign an array to variable aoColumns, do the following:
var aoColumns = [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
]
Same thing for fnCreatedRow.
If you are trying to create a JavaScript object with the two elements mentioned above instead, take a look at the other answers.

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