jQuery sort `.append()` dict dynamically by key? - javascript

How to sort .append() items dynamically by questionsId? I use below code to get aggregated data, for example, each quessionId has many related reasons. Below is my partial code of .js code in jQuery:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
var d = 0;
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
d++;
var info = lc;
console.log('info', info);
$('.tags_question').append(d + '['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>

Related

SBOX_FATAL_MEMORY_EXCEEDED

I wrote a code in javascript to export the report to excel using html. it works for 1 report but when I run multiple reports at the same place using for loop and try to export it to excel it gives me an SBOX_FATAL_MEMORY_EXCEEDED error.
Please help me with it.
function updateReportHidden(idCount) {
if (idCount > 0) {
var template = "";
for (var a = 0; a <= idCount; a++) {
template[a] = "<html><head><title>Document</title><script>window.chartAnimation = false;<\/script></head><body>" + $("#report" + a).html() + "</body></html>";
}
for (var b = 0; b <= idCount; b++) {
var temp = $(".container div .hide");
temp.remove();
$("table").attr("border", "1");
$(".container div").append(temp);
$('#ReportHidden' + b).val("");
$('#ReportHidden' + b).val(template[b]);
}
} else {
$('#ReportHidden0').val("");
var temp = $(".container div .hide");
temp.remove();
$("table").attr("border", "1");
var template = "<html><head><title>Document</title><script>window.chartAnimation = false;<\/script></head><body>" + $("#report0").html() + "</body></html>";
$('#ReportHidden0').val(template);
$(".container div").append(temp);
}
};

Looping error in Javascript with eventHandler

I have the following Javascript code within and HTML page. Its function is to display elements on the form based on the user pressing a + button and if the element is not needed then it removes it via the user pressing the - button. Currently its throwing an error "TypeError: docs[n]" is undefined after the following sequence of events:
Select button to add elements
Remove elements not needed
Add elements back (Error Thrown)
Any help would be most appreciated
`<script language="JavaScript">`
var idx = 0;
var d;
//Make getElementsByClassName work for all of IE revs
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
function add_fields(e) {
// for some reason, adding the new fields wipes out existing values, so save and restore
var docs = document.getElementsByClassName("doc");
var revs = document.getElementsByClassName("rev");
++idx;
/* console.log("test " + idx); */
var saveDocs = new Array(idx);
var saveRevs = new Array(idx);
for (n=0; n < idx; n++) {
saveDocs[n] = docs[n].value; **//Error is thrown here**
saveRevs[n] = revs[n].value;
}
node = document.getElementById("content");
theNewRow = document.createElement("tr");
theNewCell = theNewRow.insertCell(0);
theNewCell.innerHTML = "Approver Name";
theNewCell.setAttribute("style","font-size: 12pt");
theNewCell1 = theNewRow.insertCell(1);
theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
theNewCell1.setAttribute("style","padding-left: 10px");
theNewCell2 = theNewRow.insertCell(2);
theNewCell2.innerHTML = "Approver Email";
theNewCell2.setAttribute("style","font-size: 12pt");
theNewCell2.setAttribute("style","padding-left: 10px");
theNewCell3 = theNewRow.insertCell(3);
theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/> <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
theNewCell3.setAttribute("style","padding-left: 0px");
node.appendChild( theNewRow );
// restore old arrays and add the id tags to the fields just added
docs = document.getElementsByClassName("doc");
revs = document.getElementsByClassName("rev");
for (n=0; n < idx; n++) {
docs[n].value = saveDocs[n];
revs[n].value = saveRevs[n];
}
docs[idx].id = "docNum" + idx;
revs[idx].id = "rev" + idx;
}
//for Loop the entries
function myfunction() {
alert('Inside Function')
var values = "";
for (n=0; n <= idx; n++)
{
var doc = document.getElementById("docNum"+n).value;
var rev = document.getElementById("rev"+n).value;
//alert(doc+rev);
//Call VbScript Sub and pass value
PassValues(doc,rev);
```
If you've removed all the docs, document.getElementsByClassName("doc"); is going to return an empty array. If you're incrementing idx before your loop, the loop will execute once and try to access docs[0], which is undefined.

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

reading values from XML Jquery

I have uploaded the XML screenshot. The structure of the xml is divided into levels, So based on a level I need only the levels which are below it.
For example level 1 can be identified by Name and Code tag so I want level 2 of a specific level 1 for which the code matches.
I have written the Javascript for parsing this XML but I am not get what I need
$('#permissionproperty_1').on("change",function () {
var code = $(this).val().trim();
var i;
var xmlDoc;
//var xml = "<rss version='2.0'>" + $('#hidXML').val() + "</rss>";
var xml = "<xml version='1.0'>" + $('#hidXML').val() + "</xml>";
var xmlDoc = $.parseXML(xml);
var nodes = $(xmlDoc).find('Node')
//alert(nodes.length);
for (j = 0; j < nodes.length; j++) {
var level = nodes[j].getAttribute('level');
if (level == 1) {
var name = nodes[j];
var na = $(name).length;
var child = $(name).find('Code').text().trim();
if (child.indexOf(code) != -1) {
for (i = 0; i < na; i++) {
var level1 = nodes[i].getAttribute('level');
if (level1 == 2) {
var name1 = $(node[i]).find('Node').find('Name').text().trim();
var code1 = $(node[i]).find('Node').find('Code').text().trim();
alert(name1 + " : Name code :" + code1);
}
}
}
}
}
});

Push data to different elements, depending on column in google spreadsheet with GAS?

I am working in Google Spreadsheet with GAS, and I am trying to push some data from a spreadsheet to an HTML page, and right now that is working. But I am managing to do is grabbing all the values, and each time it hits a new row, it grabs all the values in that row pushes them into a newly created <div>. But I would like to do is have some column functionality also so that the different columns gets pushed to a different element like an <input> or a <select> element.
I tried out some things where I declared some variables for the desired columns, and trying to pushing them to the HTML one by one, but it didn't work out.
Here is my data:
This is what it looks like in the HTML:
This is what I am going for:
Would it be better to publish this into tables? Because I simply thought of creating divs with classes and set their width and line breaks?
Below is the code I described in the beginning:
Code.gs
var ss = SpreadsheetApp.openById("1c7IwmyBrbNq5xwzo-7EyFewCx31WpfP4EzLpkHawffI");
function doGet(request) {
return HtmlService.createTemplateFromFile('stuff')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getStitchOrders(){
var ordersName = [];
var sheet = ss.getSheetByName("Cat1");
var subRange = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn());
var orders = subRange.getValues();
for (var i = 0; i < orders.length; i++) {
ordersName.push( orders[i] )
}
return ordersName;
}
stuff.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="orders">
//Data is listed here.
</div>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOrderList).getStitchOrders();
});
function buildOrderList(ordersName) {
var rows = $('#orders');
for (var i = 0; i < ordersName.length; i++) {
rows.append('<div name="' + ordersName[i] + '">' + ordersName[i] + '</div>');
}
}
</script>
Any suggestions?
Edit
Code2.gs
var ss = SpreadsheetApp.openById("1c7IwmyBrbNq5xwzo-7EyFewCx31WpfP4EzLpkHawffI");
function doGet(request) {
return HtmlService.createTemplateFromFile('stuff2')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getStitchOrders(){
var ordersName = [];
var sheet = ss.getSheetByName("Sheet");
var subRange = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn());
var orders = subRange.getValues();
for (var i = 0; i < orders.length; i++) {
ordersName.push( {
name: orders[i][0],
status: orders[i][1],
comment: orders[i][2]
} );
}
return JSON.stringify(ordersName);
}
stuff2.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="orders">
</div>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOrderList).getStitchOrders();
});
function buildOrderList(ordersName) {
var arr = JSON.Parse(ordersName);
var rows = $('#orders');
for (var i = 0; i < arr.length; i++) {
rows.append('<div name="' + arr[i].name + '">' + arr[i].name + '</div>');
}
}
</script>
consider returning the data with this type of pattern:
for (var i = 0; i < orders.length; i++) {
ordersName.push( {
name: orders[i][0],
status: orders[i][1],
comment: orders[i][2]
} );
}
return JSON.stringify(ordersName);
then back in the client-side JS we can turn it back into an Array to loop through:
function buildOrderList(ordersName) {
var arr = JSON.parse(ordersName);
var rows = $('#orders');
for (var i = 0; i < arr.length; i++) {
// values can now be referenced via...
// arr[i].name
// arr[i].status;
// arr[i].comment;
rows.append(...);
}
}
how to then style the divs and the elements inside them to align up like a table is more a CSS question.

Categories

Resources