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>"; } },
]
Related
Yesterday i post a question ask about my addrow button.Problem solved.
It run smoothly,but I have new problems.
Firstly, my delete button which I was used the remove()API is not working.
Secondly, everytime I reload the page, in the first row col5 will have the value : undefined
Once again, I appreciate every answer to this question.
var table = null;
var arrData = [];
var arrDataPG = [];
arrData.push({
STT: 1,
id: 1,
product_type: "",
condition1: "",
rebate: 0.0,
});
$(document).ready(function () {
InitTable();
});
function InitTable() {
if (table !== null && table !== undefined) {
table.destroy();
}
table = $('#tableh').DataTable({
data: arrData,
"columns": [
{ "width": "25px" },
{ "width": "300px" },
{ "width": "300px" },
{ "width": "120px" },
{ "width": "200px" },
{ "width": "25px" },
],
columnDefs: [
{
title: "STT",
targets: 0,
data: null,
render: function (data, type, row, meta) {
return (meta.row + meta.settings._iDisplayStart + 1);
},
},
{
title: "Loại sản phẩm*",
targets: 1,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="product_type' + data.id + '" type="text" onchange="ChangeProductType(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.product_type + '">' + data.product_type + '</textarea>';
}
},
{
title: "Điều kiện*",
targets: 2,
data: null,
render: function (data, type, row, meta) {
return '<textarea style="width: 300px;" id="condition1' + data.id + '" type="text" onchange="ChangeCondition1(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.condition1 + '">' + data.condition1 + '</textarea>';
}
},
{
title: "Rebate(%)*",
targets: 3,
data: null,
width: "70",
render: function (data, type, row, meta) {
return '<div><input id="rebate' + data.id + '" type="number" style="width: 70px;" onchange="ChangeRebate(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.rebate + '"></div>';
}
},
{
title: "Ghi chú",
targets: 4,
data: null,
width: "250",
render: function (data, type, row, meta) {
return '<textarea style="width:200px;" id="note' + data.id + '" type="text" onchange="ChangeNote(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.note + '">' + data.note + '</textarea>';
}
},
{
title: "",
targets: 5,
data: null,
className: "dt-center",
width: "70",
render: function (data, type, row, meta) {
return '<div class="btn btn-danger removePG" style="cursor: pointer;font-size:25px;" onclick=removePG(\'' + data.id + '\')><i class="fa-solid fa-trash"></i></div>'
}
},
],
});
table.columns.adjust().draw();
}
$('#addRow').on('click', function () {
console.log(arrData.length);
if (arrData != '') {
var ida = arrData[0].id;
} else {
var ida = 1;
}
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].id > ida) {
ida = arrData[i].id;
}
};
arrData.push({
STT: ida + 1,
id: ida + 1,
product_type: "",
condition1: "",
rebate: 0.0,
note: ""
});
if (table != null) {
table.clear();
table.rows.add(arrData).draw();
}
});
$('#tableh').on('click','.removePG', function () {
var tableq = $('#table_h').DataTable();
tableq
.row($(this).parents('tr'))
.remove()
.draw();
});
function removePG(idc) {
let id = parseInt(idc);
if (arrData !== undefined) {
var find = arrData.find(function (item) {
return item.id === id;
});
if (find !== undefined) {
arrData = arrData.filter(function (item, index) {
return item.id !== id;
});
};
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="tableh" class="cell-border hover" style="width:100%"></table>
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script src="https://kit.fontawesome.com/60bf89e922.js" crossorigin="anonymous"></script>
I'm new to jQuery and looking for a solution, how to add a list of ul id = "animalsListDetails", hide / show on the HTML page and rendering this scope, when click a-ref:
function renderAnimalsList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#animalsList li').hide();
$('#animalsListDetails li').hide();
$.each(list, function (index, animals){
$('.animals').click(function () {
$(this).next().slideToggle();
}).append('<ul id="animalsList"><li> Animal Id: ' + animals.id + '<br> <ul id="animalsListDetails"><li> Name: '+ animals.animalname + '<br> Birthday: ' + animals.dateborn + '<br> Sex: ' + animals.sex + '<br> Type animal: ' + animals.typesanimalsId + '</li></ul></li></ul>');
});
}
call function:
function findAnimalByCustomerId(customerId){
console.log('findAnimalByCustomerId: ' + customerId);
$.ajax({
type: 'GET',
url: customerlistURL + '/' + customerId + '/myanimals',
dataType: "json",
success: function (data) {
console.log('findAnimalByCustomerId success: ' + customerId);
renderAnimalsList(data);
}
});
}
HTML:
<div class="animals">
</div>
If the main motive of question is to know how to add the list, following answer shows that with mocked data. If you wanna know more, please ask in comments (try to define your problem at once).
function renderAnimalsList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#animalsList li').hide();
$('#animalsListDetails li').hide();
$.each(list, function(index, animals) {
$('.animals').click(function() {
console.log(this);
$(this).next().slideToggle();
}).append('<ul id="animalsList"><li> Animal Id: ' + animals.id + '</li>');
//whith details
$('#animalsList').append('<ul id="animalsListDetails"><li>Name: ' + animals.animalname + '<br> Birthday: ' + animals.dateborn + '<br> Sex: ' + animals.sex + '<br> Type animal: ' + animals.typesanimalsId + '</li></ul>');
});
}
var animals = [{
animalname: 'Tiger',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 10
}, {
animalname: 'Tiger 2',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 11
}, {
animalname: 'Tiger 3',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 12
}]
function findAnimalByCustomerId(customerId) {
// This function is useless in this context
console.log('findAnimalByCustomerId: ' + customerId);
$.ajax({
type: 'GET',
url: customerlistURL + '/' + customerId + '/myanimals',
dataType: "json",
success: function(data) {
console.log('findAnimalByCustomerId success: ' + customerId);
renderAnimalsList(data);
}
});
}
//This ready function will be calling renderAnimalsList in same way as it will be called in above findAnimalByCustomerId
$(document).ready(function() {
renderAnimalsList(animals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="animals">
<div id="animalsList"></div>
<div id="animalsListDetails"></div>
</div>
Here is solution:
(function($, undefined){
$(function(){
$(document).ready(function(){
//bind handlers
function domHandlers() {
$('.animal-id').click(function(e){
slideToggle(e);
});
}
function renderAnimalsList(jsonData) {
var list = jsonData;
$.each(list, function (i, animal) {
$('#animalsList').append('<li> Animal Id: ' + animal.id + '</li>');
//With details:
$('#animalsList').append('<li class="animal-details hidden">' +
'Name: ' + animal.animalname + '<br>' +
'Birthday: ' + animal.dateborn + '<br>' +
' Sex: ' + animal.sex + '<br>' +
' Type animal: ' + animal.typesanimalsId + '</li>');
});
}
function slideToggle(e) {
$('.animal-details ').addClass('hidden');
$(e.target).closest('li').next().removeClass('hidden');
}
renderAnimalsList(jsonData);
domHandlers();
});
});
})
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
I have a problem with jquery.tokenInput.
This is my tokenInput code:
$(".search-betrocket").tokenInput("http://www.websitehere.com/web/search", {
searchDelay: 2000,
minChars: 3,
tokenLimit: 5,
hintText: "Buscador inteligente...",
noResultsText: "Sin resultados",
searchingText: "Buscando...",
theme: "facebook",
queryParam: "txt",
propertyToSearch: "NickName",
resultsFormatter: function(item){ return "<li>" + "<img src='" + Users.Avatar + "' title='" + item.first_name + " " + item.last_name + "' height='25px' width='25px' />" + "<div style='display: inline-block; padding-left: 10px;'><div class='full_name'>" + item.first_name + " " + item.last_name + "</div><div class='email'>" + item.email + "</div></div></li>" },
tokenFormatter: function(item) { return "<li><p>" + item.first_name + " <b style='color: red'>" + item.last_name + "</b></p></li>" }
});
The problem is de parser...
jquery not know much as to understand the json parser returned objects.
This is my code JSON result _GET request
{
Users: [
{
Id: 264,
NickName: "SirBet",
Avatar: "19b452bf3fe83e17de82b67e518361d2",
Ranking: 3233,
FirstName: "Sir",
LastName: "Bettor",
Gender: "H",
Location: "Valencia",
Description: "Acepto todo tipo de retos :)",
CountryId: 1,
Country: "España",
CountryISO: "ES",
PrivacyUpdated: 0
}
]
}
What is not is how to navigate the json object to function properly.
Ie enter via $val['Users']['0']['Nickname'] format but jquery / json.
Does anyone help me?
if ur json is...
[{Id:1, NickName:xxxx, Avatar: "19b452bf3fe83e17de82b67e518361d2", Ranking: 3233}]
then..
$.each(data, function(a, b) {
alert (b.Id);
alert (b.NickName);
alert (b.Avatar);
alert (b.Ranking);
});
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);
}