reading values from XML Jquery - javascript

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

Related

CheckBox for all and for single does not work correctly

I am trying to make an array of listing using checkbox function, the function checks if the all checkbox is clicked then put all listings in the array, if it is clicked to uncheck it pulls all array values, and if a single listing is checked it adds to the array , and if its unchecked when its single or all listing values its value from the array is taken out. Yet on the first run if all selected i cant remove a single value by selecting one checkbox, and after all are checked and unchecked i cant add a single value into array by checking a single option.
var lstsToEdit = [];
lstDisplay("act");
$(".tab-listings-selection").on("click", function() {
var lstType;
if(this.id == "mnLstAct") lstType = "act";
if(this.id == "mnLstInact") lstType = "inact";
if(this.id == "mnLstDraft") lstType = "draft";
document.getElementById("mnLstAct").style.fontWeight = "normal";
document.getElementById("mnLstInact").style.fontWeight = "normal";
document.getElementById("mnLstDraft").style.fontWeight = "normal";
this.style.fontWeight = "bold";
lstDisplay(lstType);
});
function lstDisplay(type){
document.getElementById("main").innerHTML = "";
var tblLsts = document.createElement("table");
tblLsts.setAttribute("id", "tblLsts");
$("#main").append(tblLsts);
var tblLstsHRow = tblLsts.insertRow(0);
var tblLstsHThumb = tblLstsHRow.insertCell(0);
var tblLstsHTitle = tblLstsHRow.insertCell(1);
var tblLstsHStock = tblLstsHRow.insertCell(2);
var tblLstsHPrice = tblLstsHRow.insertCell(3);
var tblLstsHExpiry = tblLstsHRow.insertCell(4);
var tblLstsHSection = tblLstsHRow.insertCell(5);
var tblLstsHAll = tblLstsHRow.insertCell(6);
tblLstsHThumb.outerHTML = "<th></th>";
tblLstsHTitle.outerHTML = "<th>Title</th>";
tblLstsHStock.outerHTML = "<th>In Stock</th>";
tblLstsHPrice.outerHTML = "<th>Price</th>";
tblLstsHExpiry.outerHTML = "<th>Expiry</th>";
tblLstsHSection.outerHTML = "<th>Section</th>";
tblLstsHAll.outerHTML = "<th>All<input id=\"lstsAllChk\" class=\"lstChk\" type=\"checkbox\"/></th>";
var lstThumb = [];
var listings;
if (type == "act") lsts = lstAct;
if (type == "inact") lsts = lstInact;
if (type == "draft") lsts = lstDraft;
for (var lstIndex = 1; lstIndex < lsts.results.length+1; lstIndex++){
var lst = lsts.results[lstIndex-1];
var row = document.getElementById("tblLsts").insertRow(lstIndex);
var colThumb = row.insertCell(0);
var colTitle = row.insertCell(1);
var colStock = row.insertCell(2);
var colPrice = row.insertCell(3);
var colExpiry = row.insertCell(4);
var colSection = row.insertCell(5);
var colSelect = row.insertCell(6);
var lstJ = JSON.parse($.ajax({url: "listings/" + lst.listing_id + ".json", async: false}).responseText);
colThumb.innerHTML = "<img src=\"" + lstJ.results[0].url_75x75 +"\">";
colTitle.innerHTML = lst.title;
colStock.innerHTML = lst.quantity;
colPrice.innerHTML = lst.price;
colSelect.innerHTML = "<input id=\"" + lst.listing_id + "\" class=\"lstChk\" type=\"checkbox\"/>";
for (var secIndex = 0; secIndex < sects.results.length; secIndex++){
if (sects.results[secIndex].shop_section_id == lst.shop_section_id)
colSection.innerHTML = sects.results[secIndex].title;
}
}
$.getScript("tableSort.js");
}
$(".lstChk").on("click", function() {
if(this.id == "lstsAllChk" && this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
//if(lstsToEdit.findIndex( function(value){ value == lstId;}) == -1){;
$("#"+lstId).prop("checked");
lstsToEdit.push(lstId);
//}
}
}
else if(this.id == "lstsAllChk" && !this.checked){
for(var lstIndex = 0; lstIndex < document.querySelectorAll(".lstChk").length; lstIndex++){
var lstId = document.querySelectorAll(".lstChk")[lstIndex].id;
$("#"+lstId).prop("checked", false);
var index = lstsToEdit.findIndex( function(value){ value == lstId;});
lstsToEdit.splice(index, 1);
}
}
else if(this.checked) lstsToEdit.push(this.id);
else {
var index = lstsToEdit.findIndex( function(value){ value == this.id;});
lstsToEdit.splice(index, 1);
}
if(lstsToEdit.length > 0) document.getElementById("lstEdit").style.display = "block";
else document.getElementById("lstEdit").style.display = "none";
console.log(lstsToEdit);
});
table sort js
$("th").on("click", function() {
var table = this.closest("table");
var selection = $(this).text();
var col = this.cellIndex;
var tbl = [];
var order = [];
for (var rowIndex = 0; rowIndex < table.rows.length; rowIndex++){
if (rowIndex > 0){
tbl.push([]);
for (var colIndex = 0; colIndex < table.rows[rowIndex].cells.length; colIndex++){
tbl[rowIndex-1].push(table.rows[rowIndex].cells[colIndex].innerHTML);
if (colIndex == col){
order.push([]);
order[rowIndex-1].push(tbl[rowIndex-1][colIndex]);
order[rowIndex-1].push(rowIndex-1);
}
}
}
}
for (var rowIndex = table.rows.length-1; rowIndex > 0; rowIndex--){
table.deleteRow(rowIndex);
}
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g
order.sort (function (a,b){
var aA = a[0].replace(reA, "").toLowerCase();
var bA = b[0].replace(reA, "").toLowerCase();
if(aA == bA) {
var aN = parseInt(a[0].replace(reN, ""), 10);
var bN = parseInt(b[0].replace(reN, ""), 10);
return aN == bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
};
});
for (var orderIndex = 0; orderIndex < order.length; orderIndex++){
var row = table.insertRow(orderIndex + 1);
for (var colIndex = 0; colIndex < tbl[orderIndex].length; colIndex++){
var cell = row.insertCell(colIndex);
var index = order[orderIndex][1];
cell.innerHTML = tbl[index][colIndex];
}
}
});
index
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
include 'menu.php';
include 'shopJson.php';
?>
<div id="lstEdit">edit</div>
<div id="main"></div>
</body>
</html>
<script>
var lstActURL = "listings/active.json";
var lstInactURL = "listings/inactive.json";
var lstDraftURL = "listings/draft.json";
var sectURL = "listings/sect.json";
var lstAct = JSON.parse($.ajax({url: lstActURL, async: false}).responseText);
var lstInact = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var lstDraft = JSON.parse($.ajax({url: lstInactURL, async: false}).responseText);
var sects = JSON.parse($.ajax({url: sectURL, async: false}).responseText);
$("#mnLstAct").append("(" + lstAct.results.length + ")");
$("#mnLstInact").append("(" + lstInact.results.length + ")");
$("#mnLstDraft").append("(" + lstDraft.results.length + ")");
document.getElementById("mnLstAct").style.fontWeight = "bold";
$.getScript("listings.js");
</script>
The JQuery .attr() method correlates to the actual attributes of a DOM element. However, from the JavaScript perspective, many elements have DOM properties that seem like they are the same as their HTML attribute counterparts, but are not because the property is updated in memory, while the attribute change updates the DOM. Sometimes, there are properties that don't even have an attribute counterpart (i.e. selectedIndex on select elements).
The point is that you have thess lines:
$("#"+lstId).attr("checked", true);
$("#"+lstId).attr("checked", false);
Where you are attempting to force an element to be checked, but that may not correlate to what you get when you check the checked property.
To account for this, use the prop() method instead of the .attr() method:
$("#"+lstId).prop("checked", true);
$("#"+lstId).prop("checked", false);
See the documentation for .prop() for details and a comparison between attributes and properties.

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

Google Form Script Population

I am trying to populate a google form with questions scraped from a google sheet. Currently when I run my code I am getting the questions created, but only 25% or so actually have the string, the rest are simply blank. The questions that appear correctly change every time I run the script. It is seemingly random.
function formPopulation() {
var ss = SpreadsheetApp.openById("--");
var sheet = ss.getSheetByName('Tracker');
var auditTool = ss.getSheetByName('Audit Tool');
var validatorInfo = ss.getSheetByName('Validator Info');
//Sheet Info
var rows = auditTool.getLastRow(); //Number of Rows
var columns = auditTool.getLastColumn(); //Number of Columns
var startRow = 1;
var startColumn = 1;
var dataRange = auditTool.getRange(startRow, startColumn, rows, columns);
//getRange(first row of data, first column of data, last row of data, last column of data)
var data = dataRange.getValues();
//Sets working range of script
var form = FormApp.openById("--");
var item = form.addListItem();
var entityName = "";
var arrayOfEntities = [];
var newEntity = '';
for (var i = 4; i < columns; i++) {
//4 because that is where entity names begin
entityName = data[i][2];
Logger.log('entityName: ' + entityName);
newItem = item.createChoice(entityName);
arrayOfEntities.push(newItem);
};
item.setTitle("Select Entity").setChoices(arrayOfEntities);
var requirement = "";
var arrayOfRequirements = [];
var newRequirement = '';
for (var j = 5; j < rows; j++) {
//5 because that is where Requirements begin
if (data[0][j] != null) {
requirement = data[0][j];
if (requirement != "" || requirment != null){
requirement = "question #" + j;
Logger.log('requirement: ' + requirement);
form.addMultipleChoiceItem().setTitle(requirement).setChoiceValues(['Complete', 'Incomplete']);
};
};
};
};
The first question is supposed to be a multiple choice item where each 'entity' is an option. The remainder of the questions are supposed to be whether each 'requirement' is marked complete or incomplete.
Here is the spreadsheet I am working from
you have a typo:
if (requirement != "" || requirment != null){
should be 'requirement'
Here in last forloop
requirement = "question #" + j;
Please verify, is it ok ? or you should use
requirement = "question #" + j + ' ' +data[0][j];

Iterate over gmail threads and add a label with addlabel

I wish to run this standalone code twice a day, but cannot solve the exception on the addLabel, which is "impossible to find the method", any suggestion? I tried to change the for cycle as well as to assign a var to the threads[i] but nothing changed.
function salvaNote(){
var d = new Date();
d.setMonth(d.getMonth()-6);
var n = d.getFullYear() + "/" + addZero(d.getMonth()+1) + "/" + addZero(d.getDate());
var folderName = 'tavoloTecnico';
labelName = GmailApp.createLabel('tavoloTecnico');
var query = 'in:anywhere from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it has:attachment subject:previsioni filename:xls '+ 'after:'+n;
var threads = GmailApp.search(query);
var quanteMail = threads.length;
for ( var i = 0 ; i < quanteMail; i++) {
threads[i].addLabel(labelName);
var mesgs = threads[i].getMessages();
for(var j in mesgs){
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
}

How do I bold one line in a Google Docs Script?

I'm writing a script to parse a Google Sheet and format the cells nicely on a Doc. I'd like the cell data from column 1 to always be bold and the cell data from column 6 to always be Italic. The problem is, after appending a paragraph to the document body, the attribute changes are applied to the entire document. Is there a way to bold/italicize the cell data before appending it to the doc body?
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();
for (var i = 2; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++){
var cellData = rows.getCell(i, j).getValue()
// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).editAsText().setBold(true);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).editAsText().setItalic(true);
} else {
docBody.appendParagraph(cellData);
}
}
}
};
EDIT: Try #2, using the setAttributes method
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();
for (var i = 2; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++){
var cellData = rows.getCell(i, j).getValue()
// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).setAttributes(style1);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).setAttributes(style2);
} else {
docBody.appendParagraph(cellData);
}
}
}
};
// Style definitions as global variables
var style1= {};
style1[DocumentApp.Attribute.BOLD] = true;
var style2= {};
style2[DocumentApp.Attribute.ITALIC] = true;
If you use style attributes you can assign a style to every paragraph very easily, you can actually do it for any document element...
Here is a basic example code to show how it works :
(doc here)
function exportToDoc(){
var doc = DocumentApp.openById('16i----L53WTDpzuLyhqQQ_E');// or create a new doc (but not while you test it :-)
var body = doc.getBody();
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getDataRange().getValues();
for (var i in values){
var rowData = values[i].join(' + ');
if (i == 1) {
body.appendParagraph(rowData).setAttributes(style2);
} else if (i == 2 ) {
body.appendParagraph(rowData).setAttributes(style1)
}
}
doc.saveAndClose();
}
// Style definitions as global variables
var style1 = {};// style example 1
style1[DocumentApp.Attribute.FONT_SIZE] = 10;
style1[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.CONSOLAS;
style1[DocumentApp.Attribute.FOREGROUND_COLOR] = "#444400";
var style2 = {};// style example 2
style2[DocumentApp.Attribute.FONT_SIZE] = 16;
style2[DocumentApp.Attribute.FONT_FAMILY] =DocumentApp.FontFamily.ARIAL_NARROW;
style2[DocumentApp.Attribute.FOREGROUND_COLOR] = "#005500";
//
example random data result :

Categories

Resources