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

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 :

Related

Deleting row in one sheet if cell value is found in another sheet

I am trying to delete rows if cell value is found in another sheet via App Script. But the code is not going through complete data in history sheet.
function deleteOld1() {
var app = SpreadsheetApp;
var orderSheet = app.getActiveSpreadsheet().getSheetByName("RC"); \sheet where to look
var historySheet = app.getActiveSpreadsheet().getSheetByName("OB"); \sheet from which data has to be deleted
var lastRow = historySheet.getLastRow();
var lastRow1 = orderSheet.getLastRow();
var poNO = orderSheet.getRange("A2:A" + lastRow);
var myRange = historySheet.getRange("A2:A" + lastRow1);
var row = poNO.getRow();
var col = poNO.getColumn();
var data = myRange.getValues();
var data1 = poNO.getValues();
if (col>= poNO.getColumn() && col <= poNO.getColumn() && row>= poNO.getRow() && row <= poNO.getRow()){
for (i=0; i<data.length; i++) {
for (j=0; j<data1.length; j++){
if(data[i][0] == data1[j][0]){
historySheet.deleteRow(i+2);
}
}
}
}
}
Please go through this code and help

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.

Change Row Alignment Based on Cell Value - Google Scripts

the following script is supposed to change the row alignment in a Google sheet to 'right' if the value of column E in the row is 'Post.' When I run the script it does not pop any errors, however, it does not do anything either.
Can anyone take a look at the below and provide some guidance?
Thanks!
function rowLoop() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("KOD Tests");
var endRow = ss.getLastRow();
for (var r = 1; r < endRow; r++) {
rowAlignment(r);
}
}
function rowAlignment(r) {
var sheet = SpreadsheetApp.getActiveSheet();
var c = sheet.getLastColumn();
var dataRange = sheet.getRange(r, 1, 1, c);
var data = dataRange.getValue();
var row = data[4];
if(row === 'Post') {
data.setHorizontalAlignment('right');
}
SpreadsheetApp.flush();
}
Here it is with a few things fixed (please see comments)
function rowLoop() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var endRow = ss.getLastRow();
// <= to repeat for all rows
for (var r = 1; r <= endRow; r++) {
rowAlignment(r);
}
}
function rowAlignment(r) {
var sheet = SpreadsheetApp.getActiveSheet();
var c = sheet.getLastColumn();
var row = sheet.getRange(r, 1, 1, c);
// Get cell in column E of row
var cell=row.getCell(1,5);
// Get its value
var data = cell.getValue();
// Test equal to 'Post' with ==
if(data == 'Post') {
row.setHorizontalAlignment('right');
}
SpreadsheetApp.flush();
}

Returning cell value based on Radio selection

The goal I am trying to achieve is to retrieve a cell value based on a form radio selection and update a text area.
Process: User opens dialog box. They select a field office. Onclick runs the function check. After check runs google.script.run.withSuccessHandler(addSignatureLine).getSignatureLine(cellElement); is supposed to run and update the textarea with the Id 'AdditionalMessage' with the signature line retrieved from .getSignatureLine.
Here are two functions of the html code:
<script>
function addSignatureLine(signatureLine){
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
};
function updateSignatureLine() {
var cellElement = document.getElementById('ET');
console.log('cellElement: ' + cellElement);
google.script.run.withSuccessHandler(addSignatureLine)
.getSignatureLine(cellElement);
};
function check() {
var ele = document.getElementsByName('fieldOfficeET');
var flag = 0;
for (var i = 0; i < ele.length; i++) {
if (ele[i].checked)
flag = 1;
}
if (flag == 1)
document.getElementById('Submit').disabled = false;
};
</script>
Here is the getSignatureLine.gs script
function getSignatureLine(cellObject) {
var ss = SpreadsheetApp.openById('googleSheetId');
var sheet = ss.getSheetByName('AMS Contact Information');
var firstRow = 2;
var lastRow = 10;
var dataRange = sheet.getRange(firstRow, 1, lastRow, 11);
var dataValues = dataRange.getValues();
for (var key in cellObject) { //Loop through all the data in the form
Logger.log('key: ' + key);
Logger.log('value: ' + cellObject[key]);
}
//Determines the row the Field Office is in
for (var rr = 0; rr < dataValues.length; rr++) {
if (dataValues[rr][0] == cellObject.fieldOfficeET) {
var r = rr + 2
break;
}
}
var signatureLine = sheet.getRange(r, 11).getValue();
Logger.log("signatureLine: " + signatureLine)
return signatureLine;
}
There is a problem with this line:
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
I would try:
document.getElementById('AdditionalMessage').value = '\n\n' + signatureLine;
Add a plus sign to concatenate the text.

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

Categories

Resources