how to create a hierarchy table with parent child rows razor - javascript

here is my table snap enter image description here
I am creating this table from my model in razor view
it shows the structure of task and sub-tasks and their subtask ...
but the problem is it loads sub task and their subtask ... in the same level when someone clicks on the first column it loads its child under the parent
it's loads them and add a table row under the correspondence row
here is my jquery code I want to make it hierarchical like there should be a difference in parent and child level
function showHierarchy(taskId) {
if ($('.subtaskof_' + taskId).text() == '') {
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId, // request url
{
async: false,
success: function (data, status, xhr) {// success callback function
var subtasklist = JSON.parse(data)
console.log(subtasklist);
for (i = 0; i < subtasklist.length; i++) {
subtask = subtasklist[i];
var therowis = '<tr class=subtaskof_' + taskId + '>'
+ '<td id="subtaskrow_' + subtask['InstanceId'] + '" align="right">_</td>'
+ '<td>' + subtask['InstanceId'] + '</td>'
+ '<td>' + subtask["Title"] + '</td>'
+ '<td>' + subtask["Deliverables"] + '</td>'
+ '<td>' + subtask["StartDate"] + '</td>'
+ '<td>' + subtask["Priority"] + '</td>'
+ '<td>' + subtask["State"] + '</td>'
+ '<td>See Details_subt</td>'
+ '<td>Add Sub Task_subt</td>'
+ '</tr>'
// Find position to add new subtask row in the Task table
$("#my-grid tr").filter(function () {
if ($(this).text().indexOf(taskId) >= 0) {
$(this).after(therowis);
issubsubtaskexists = false;
console.log("chield checking for - " + subtask['InstanceId'])
$.ajax('/Tasks/sfsubtasks?taskId=' + subtask['InstanceId'], // request url
{
async: false,
success: function (data_, status_, xhr_) {
if (data_.length > 0) {
console.log("The data_ is - " + data_);
var subsubtasklist = JSON.parse(data_);
console.log("The subsubtasklist is - " + subsubtasklist)
console.log("lenght for - " + subtask['InstanceId'] + " , is - " + subsubtasklist);
if (subsubtasklist.length > 0) {
$('#subtaskrow_' + subtask['InstanceId']).html("<b><a style='font-size:25px; padding-left:17px;' id='lnk_" + subtask['InstanceId'] + "' href='#' onclick='showHierarchy(" + subtask['InstanceId'] + ")'> + </a></b>")
issubsubtaskexists = true;
}
}
}
});
console.log("The taskId is - "+taskId)
$('#lnk_' + taskId).html('<b>_</b>');
}
});
}
}
});
} else {
// Toggle/removing subtasks
$('.subtaskof_' + taskId).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId,
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist = JSON.parse(data)
console.log(subsubtasklist);
for (i = 0; i < subsubtasklist.length; i++) {
$('.subtaskof_' + subsubtasklist[i]['InstanceId']).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + subsubtasklist[i],
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist_ = JSON.parse(data)
console.log(subsubtasklist_);
for (j = 0; j < subsubtasklist_.length; j++) {
$('.subtaskof_' + subsubtasklist_[j]['InstanceId']).remove();
}
}
});
}
}
});
$('#lnk_' + taskId).html('<b>+</b>');
}
}
plz let me know what can be done of this table for showing data hierarchically

Related

Remove duplicate rows based on 3 columns

The below code returns a table with values from a web list. Some values are duplicates. I need to remove all duplicates where "User_x0020_Name", "Previous_Total_Most_Likely_Forec", "Submitted_Total_Most_Likely_Fore" are the same and only keep the latest record (maximum of "Created") for a duplicates set.
function loadAuditTrailFinancials() {
var auditTrailURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Audit_Trail_Financial_Data')/items?$select=Author/Title,Previous_Total_Most_Likely_Forec,Submitted_Total_Most_Likely_Fore,Forecast_Approval_Reason,Title,Created,Workflow_Stage_Name,WorkflowStageShort,Source,Event&$filter=Title eq '" + PDP_projUid + "'&$orderby=Created desc&$expand=Author/ID";
console.log("loadAuditTrailFinancials:" + auditTrailURL);
$.ajax({
url: auditTrailURL,
method: "GET",
headers: {"Accept": "application/json; odata=verbose"},
success: function (data) {
var items = data.d.results;
for (var i = 0; i < items.length; i++) {
var creation_date = items[i].Created;
var current_user = items[i].User_x0020_Name;
console.log(items[i]);
$('#AuditTrailTable_Financial').append('<tr class="audit_content">' +
'<td align=center> ' + format_date(creation_date) + ' </td>' +
'<td align=center> ' + items[i].WorkflowStageShort+ ' </td>' +
'<td align=center> ' + items[i].Author.Title + ' </td>' +
'<td align=center> ' + items[i].Source + ' </td>' +
'<td align=center> ' + items[i].Previous_Total_Most_Likely_Forec + ' </td>' +
'<td align=center> ' + items[i].Submitted_Total_Most_Likely_Fore + ' </td>' +
'</tr>');
}
$('.audit_content').hide();
console.log(data);
},
error: function (data) { alert("Some error occurred in getting Audit Trail")}
});
}
//apply a filter on data.d.result array
var items = data.d.results.filter(function (el, i, arr) {
//if index match then this element is keeped
//arr is the array on which filter was called (is data.d.result)
return i === arr.findIndex(function (obj) {
//need to satisfies this conditions
return obj.User_x0020_Name === el.User_x0020_Name &&
obj.Previous_Total_Most_Likely_Forec === el.Previous_Total_Most_Likely_Forec &&
obj.Submitted_Total_Most_Likely_Fore === el.Submitted_Total_Most_Likely_Fore &&
obj.Created >= el.Created;
})
});
reference:
Array.prototype.filter()
Array.prototype.findIndex()
Maybe you can do this using a hash map to store index location of the unique triplet in order to replace it when we find a newer one.
// This will be our final result array, with no duplicates.
const result = []
// Here we will store the result index location of a stored item.
const latest_map = new Map()
// build a unique key for the triplet combo.
function buildKey(item) {
const separator = "__"
return item.User_x0020_Name + separator + item.Previous_Total_Most_Likely_Forec + separator + item.Submitted_Total_Most_Likely_Fore
}
// check if item exist, replace
function deduplicateAndKeepLatest(item) {
const key = buildKey(item);
if (latest_map.has(key)) {
result[latest_map.get(key)] = item; // replace old item with latest.
} else {
result.push(item);
latest_map.set(key, result.length-1) // first time seeing this item, save the index it was stored at.
}
}
// make sure items is in the correct sort order, since you want to keep the latest.
items.forEach((item) => {
deduplicateAndKeepLatest(item);
}
return result; // should contain unique triplet, and only latest one.
Thank you everyone for your replies.
I have sorted the table in descending order and used the below code to solve the issue:
function (data) {
var items = data.d.results;
var current_user = "";
var current_Previous_Total = 0;
var current_Submitted_Total = 0;
for (var i = 0; i < items.length; i++) {
var creation_date = items[i].Created;
if (current_user != items[i].User_x0020_Name || current_Previous_Total != items[i].Previous_Total_Most_Likely_Forec || current_Submitted_Total != items[i].Submitted_Total_Most_Likely_Fore) {
current_user = items[i].User_x0020_Name;
current_Previous_Total = items[i].Previous_Total_Most_Likely_Forec;
current_Submitted_Total = items[i].Submitted_Total_Most_Likely_Fore;
$('#AuditTrailTable_Financial').append('<tr class="audit_content">' +
'<td id="tdDate" align=center> ' + format_date(creation_date) + ' </td>' +
'<td id="tdStage" align=center> ' + items[i].WorkflowStageShort+ ' </td>' +
'<td id="tdUser" align=center> ' + items[i].Author.Title + ' </td>' +
'<td id="tdSource" align=center> ' + items[i].Source + ' </td>' +
'<td id="tdPrevious" align=center> ' + items[i].Previous_Total_Most_Likely_Forec + ' </td>' +
'<td id="tdSubmitted" align=center> ' + items[i].Submitted_Total_Most_Likely_Fore + ' </td>' +
'</tr>');
}
}
$('.audit_content').hide();
console.log(data);
},

How can I check checkbox which is exists in model sepereted by coma from database (as shown below in code) using MVC asp.net?

Below is code of javascript. I want my checkboxes are selected based on coma seperated values from database. please let me know where i am mistaken
function GetStatesList() {
debugger;
var makeList = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function(stateList) {
var makeChkList = ""
for (var i = 0; i < stateList.length; i++) {
var st = stateList[i];
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=\"" + #Model.States.Contains("Alaska") ? "checked" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function(r) {
OnFailure(r);
},
failure: function(r) {
OnFailure(r);
}
});
}
I found issue. because of js is client side and model loads before js load it was not getting modal value and to get value we have to use this line
#Html.Raw(Json.Encode(Model.States));
function GetStatesList() {
debugger;
var arrstates = [];
var url = '/IAAISettings/GetStatesList';
$.ajax({
type: 'POST',
url: url,
success: function (stateList) {
var makeChkList = ""
var st =#Html.Raw(Json.Encode(Model.States));
arrstates = st.split(",");
console.log(st);
for (var i = 0; i < stateList.length; i++) {
var str = stateList[i];
if (arrstates.includes(stateList[i])) {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + stateList[i] + "\" name=\"State_" + stateList[i] + "\" checked=checked\"" + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
else {
makeChkList += "<div class=\"col-12\">" +
"<label class=\"checkbox\">" +
"<input type=\"checkbox\" id=\"State_" + i + "\" name=\"State_" + i + "\" value=\"" + stateList[i] + "\">" +
"<i></i>" + stateList[i] +
"</label>" +
"</div>";
}
}
document.getElementById('StateschkList').innerHTML = makeChkList;
},
error: function (r) {
OnFailure(r);
},
failure: function (r) {
OnFailure(r);
}
});
}

control entering in loop but not appending and displaying data in html div

i have json data which i want to display in html div using for loop. my control in entering in loop but not appending and displaying data in html div.
json data;
[{"id":"15","FirstName":"ranjan","MiddleName":"","LastName":"","Gender":"","Location":"r","Email":"ranjan.gupta.1994#gmail.com","Mobile":""},{"BookTitle":"","BookGenre":"","BookWriter":"","BookDescription":""}]
code;
$.getJSON(url, function(data) {
console.log(data);
if (data) {
alert("hey got the data" + JSON.stringify(data));
for (var i = 0; i < data.length; i++) {
alert("entered");
alert("hey got the data" + JSON.stringify(data[1]));
var $appendData =
$('<div id="' + data[i].id + '">' + '<p>'
+ 'FirstName:' + data[i].data.FirstName + '<br/>'
+ 'MiddleName:' + data[i].data.MiddleName + '<br/>'
+ 'LastName:' + data[i].data.LastName + '<br/>'
+ 'Gender:' + data[i].data.Gender + '<br/>'
+ 'Location:' + data[i].data.Location + '<br/>'
+ 'Email:' + data[i].data.Email + '<br/>'
+ 'Mobile:' + data[i].data.Mobile + '<br/>'
+ '</p>' + '</div>').appendTo('#postjson');
}
} else {
return;
}
// this is my div
</script>
<div class="grid" id="postjson"></div>
</div>
</div>
You got typo on your loop, just replace all your data[i].data.property with data[i].property
Javascript
$.getJSON(url,function(data) {
console.log(data);
if(data){
alert("hey got the data"+JSON.stringify(data));
for(var i=0; i<data.length; i++) {
alert("entered");
alert("hey got the data"+JSON.stringify(data[1]));
$('<div id="'+data[i].id+'">'
+'<p>'
+'FirstName:'+data[i].FirstName+'<br/>'
+'MiddleName:'+data[i].MiddleName+'<br/>'
+'LastName:'+data[i].LastName+'<br/>'
+'Gender:'+data[i].Gender+'<br/>'
+'Location:'+data[i].Location+'<br/>'
+'Email:'+data[i].Email+'<br/>'
+'Mobile:'+data[i].Mobile+'<br/>'
+'</p>'
+'</div>').appendTo('#postjson');
}
}
else {
return;
}
JsFiddle

Why javascript actionlink function under ajax not work in mvc

Under an ajax get method i need to generate table programatically.why actionlink not work with my table
ajax method
$(document).ready(function () {
//click event
$('.delete-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
//click event
$('.edit-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
$('.submitDetailForm').on('click', function () {
//get value from control
var ProductID = $('#ProductID').val();
var Qty = $('#Qty').val();
var Unit = $('#Unit').val();
var Amount = $('#Amount').val();
var ICMS = $('#ICMS').val();
var IPI = $('#IPI').val();
var ProductName = $('#ProductID option:selected').text();
var booksDiv = $("#booksDiv");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("AddToCard", "Sales")',
data: { ProductID: ProductID, ProductName: ProductName, Qty: Qty, Unit: Unit, Amount: Amount, ICMS: ICMS, IPI: IPI },
success: function (data) {
console.log(data);
var result = "";
booksDiv.html('');
$.each(data, function (SalesOrderID, OrderDetails) {
result += '<tr> <td>' + OrderDetails.Name + '</td>' +
'<td>' + OrderDetails.Qty + '</td>' +
'<td>' + OrderDetails.Unit + '</td>' +
'<td>' + OrderDetails.Amount + '</td>' +
'<td>' + OrderDetails.ICMS + '</td>' +
'<td>' + OrderDetails.IPI + '</td>' +
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>' +
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>' +
' </tr>';
});
booksDiv.html(result);
},
error: function (xhr, AJAXOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
});
});
Hyper link content
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>'
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>'
hyperlink display perfectly in browser but can not invoke click events
why my actionlink click event are not fired?
You need to use event delegation (using the .on() function) when adding dynamic content
$('#booksDiv').on('click', '.delete-logo', function() {
....
});
$('#booksDiv').on('click', '.edit-logo', function() {
....
});
where the element with id="booksDiv" is the closest ancestor that exists when the page is first generated.
Side note: Rather than manually generating your javascript object, you can simply use data: $('form').serialize(),

How to return a value from javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)

Categories