I am trying to add validation, specifically text validation, for my google form text items.
However, it looks to me like the 'setValidation()' function only works with items with known type like TextItem.
To my understanding, if I pull a form item via 'getItemById()', I would get a generic item. It still has 'TEXT' type but google script just doesn't see it as a TextItem and therefore the 'setValidation()' function is not available for it.
I have tried doing thing like .asTextItem() with no luck. Here is an example script that fails to run because of an error
'TypeError: Cannot find function setValidation in object Item. (line
10, file "Code")' on line 9.
function validationTest() {
var form = FormApp.getActiveForm();
var items = form.getItems();
var textValidation = FormApp.createTextValidation()
.requireNumberGreaterThanOrEqualTo(0)
.requireWholeNumber();
for (var i = 0; i<items.length; i++) {
items[i].asTextItem();
items[i].setValidation(textValidation);
};
}
So, is there a known solution or workaround for this issue? Thank you in advance.
SC
You should add .build() at the end of your validation builder, as it's shown here.
Also, asTextItem should be called simultaneously with setValidation:
function validationTest() {
var form = FormApp.getActiveForm();
var items = form.getItems();
var textValidation = FormApp.createTextValidation()
.requireNumberGreaterThanOrEqualTo(0)
.requireWholeNumber()
.build();
for (var i = 0; i<items.length; i++) {
items[i].asTextItem().setValidation(textValidation);
};
}
Related
I'm trying to make a runnable console command through Chrome that searches for the word "takeID", and then grabs the content immediately after it between = and & from a div class.
What I have so far doesn't work because I'm very bad at JS so any help would be appreciated. Below is what I have so far:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var searchValue = "takeID";
for(var i=0;i<iframe.length;i++){ if(iframe[i].innerHTML.indexOf(searchValue)>-1){}};
var subString = iframe.substring( iframe.lastIndexOf("=")+1, iframe.lastIndexOf("&"));
console.log(searchValue+"="+subString);
An example of the div class it would be searching would look like:
<div class="activity activity-container-html5" config="{example text;takeID=cd251erwera34a&more example text}">
There are two issues with the code. The first issue is the searchValue posts to the console as whatever is in between the takeID, and not the actual result from searching. The second issue is that the code to search between = and & doesn't work at all and I don't know why. What is wrong with the code?
I just want an output that would post to the log or a popup window saying:
takeID=cd251erwera34a
EDIT:
Something else I thought of was how would you be able to just parse the div and then search for what is in between "takeID=" and "&"? I tried this but I was getting the error "Uncaught TypeError: iframe.lastIndexOf is not a function".
var iframe=document.getElementsByClassName("activity activity-container-html5");
var subString = iframe.substring( iframe.lastIndexOf("takeId=") + 1, iframe.lastIndexOf("&") );
console.log(subString);
I looked this up and I see this is because what it is trying to process is not a string but I'm not sure why that is or how to fix it.
I don't know about you but the best would be to use json directly inside the html tag like this:
<div class="activity activity-container-html5" config="{'example':'text', 'takeID':'cd251erwera34a', 'other':''}">
Or use an array and check manually if the one you are checking is the one you want, like this:
function config(element, searchValue) {
if (element.hasAttribute('config')) {
var configData = JSON.parse(element.getAttribute('config'));
var res = "";
for (var i = 0; i < configData.length; i++) {
if (configData[i].includes(searchValue)) {
res = configData[i];
break;
}
}
return res;
}
}
el = document.getElementsByClassName('activity activity-container-html5');
for (var i = 0; i < el.length; i++) {
console.log(config(el[i], "takeID"));
}
<div class="activity activity-container-html5" config='["example=text", "takeID=cd251erwera34a", "othertext=here"]'>
The array-type (second example) is most likely to work better than the simple json one (first one).
I figured out what I needed to do. Below is working code:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var div = "";
for(var i=0;i < iframe.length; i++){
div += (iframe[i].outerHTML);
}
var take = /takeID=([a-z0-9]*)&/;
var capture = div.match(take);
var matchID = capture[1];
console.log(matchID);
window.alert("takeID=" + matchID);
I am new to Google Scripts. So, I am trying to learn. I have used the script below from a Youtube video that shows how to write a script to create an URL when a Google form is submitted. This should allow the user to go back and re-edit the form. There is a sample script to use in the youtube information. However, when I run this script, I get the following error message.
Error TypeError: data[j][0].setMilliseconds is not a function
assignEditUrls # Code.gs:17
I saw in another post response that "j" is not a good variable. I tried changing that but no luck. Any help would be appreciated. Below is the script as written.
function assignEditUrls() {
var form = FormApp.openById('1Jh35nIdGtT0gCTWNSW4vAnC9L-cZY-pdOnHy2MFuL2g');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Event_Information');
var data = sheet.getDataRange().getValues();
var urlCol = 52;
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
setMilliseconds() is a method of Date. Your code is returning the referred method because the value returned by data[j][0] is not a Date object.
In order to help you debug your code you might include console.log(JSON.stringify(data[j][0])) before line 17.
I'm working on a project that take "profiles" stored in a Google Sheet, makes a unique Google Doc for each profile, and then updates the unique Google Doc with any new information when you push a button on the Google Sheet.
I have some other automations built into my original code, but I simplified most of it to what's pertinent to the error I'm getting, which is this:
Exception: Document is missing (perhaps it was deleted, or you don't have read access?
It happens on Line 52 of my script in the fileUpdate funtion. Here's the appropriate line for reference:
var file = DocumentApp.openById(fileName);
And this is the rest of my code:
function manageFiles() {
//Basic setup. Defining the range and retrieving the spreadsheet to store as an array.
var date = new Date();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var array = sheet.getDataRange().getValues();
var arrayL = sheet.getLastRow();
var arrayW = sheet.getLastColumn();
for (var i = 1; i < arrayL; i++) {
if (array[i][arrayW-2] == "") {
//Collect the data from the current sheet.
//Create the document and retrieve some information from it.
var docTitle = array[i , 0]
var doc = DocumentApp.create(docTitle);
var docBody = doc.getBody();
var docLink = doc.getUrl();
//Use a for function to collect the unique data from each cell in the row.
docBody.insertParagraph(0 , "Last Updated: "+date);
for (var j = 2; j <= arrayW; j++) {
var colName = array[0][arrayW-j];
var data = array[i][arrayW-j];
if (colName !== "Filed?") {
docBody.insertParagraph(0 , colName+": "+data);
}
}
//Insert a hyperlink to the file in the cell containing the SID
sheet.getRange(i+1 , 1).setFormula('=HYPERLINK("'+docLink+'", "'+SID+'")');
//Insert a checkbox and check it.
sheet.getRange(i+1 , arrayW-1).insertCheckboxes();
sheet.getRange(i+1 , arrayW-1).setFormula('=TRUE');
}
else if (array[i][arrayW-2] !== "") {
updateFiles(i);
}
}
sheet.getRange(1 , arrayW).setValue('Last Update: '+date);
}
//Note: I hate how cluttered updateFiles is. I'm going to clean it up later.
function fileUpdate(rowNum) {
//now you do the whole thing over again from createFiles()
//Basic setup. Defining the range and retrieving the spreadsheet to store as an array.
var date = new Date();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var array = sheet.getDataRange().getValues();
var arrayL = sheet.getLastRow();
var arrayW = sheet.getLastColumn();
//Collect the data from the current sheet.
var fileName = array[rowNum][0];
var file = DocumentApp.openById(fileName);
//retrieve the body of the document and clear the text, making it blank.
file.getBody().setText("");
//Use a for function to collect the the unique date from every non-blank cell in the row.
file.getBody().insertParagraph(0 , "Last Updated: "+date);
for (var j = 2; j <= arrayW; j++) {
var colName = array[0][arrayW-j];
var data = array[rowNum][arrayW-j];
file.getBody().insertParagraph(0 , colName+": "+data);
}
}
If you'd like to take a look at my sample spreadsheet, you can see it here. I suggest you make a copy though, because you won't have permissions to the Google Docs my script created.
I've looked at some other forums with this same error and tried several of the prescribed solutions (signing out of other Google Accounts, clearing my cookies, completing the URL with a backslash, widening permissions to everyone with the link), but to no avail.
**Note to anyone offended by my janky code or formatting: I'm self-taught, so I do apologize if my work is difficult to read.
The problem (in the updated code attached to your sheet) comes from your URL
Side Note:
In your initial question, you define DocumentApp.openById(fileName);
I assume your realized that this is not correct, since you updated
your code to DocumentApp.openByUrl(docURL);, so I will discuss the
problem of the latter in the following.
The URLs in your sheet are of the form
https://docs.google.com/open?id=1pT5kr7V11TMH0pJea281VhZg_1bOt8YDRrh9thrUV0w
while DocumentApp.openByUrl expects a URL of form
https://docs.google.com/document/d/1pT5kr7V11TMH0pJea281VhZg_1bOt8YDRrh9thrUV0w/
Just adding a / is not enough!
Either create the expected URL manually, or - much easier / use the method DocumentApp.openById(id) instead.
For this, you can extract the id from your URL as following:
var id = docURL.split("https://docs.google.com/open?id=")[1];
var file = DocumentApp.openById(id)
I'm currently working on a way to distribute updates to Google Sheets without the user having to update anything at their end. This is in line with a specification I am having to meet.
This is so far accomplished using apps script libraries and boilerplate code for each sheets bound script.
A desire has now arisen to have custom menus within the sheets, whose menu text and functions are also centrally updatable. My thoughts on how to accomplish this were to have the menu items and their associated functions defined as followed in the library.
function getMenu() {
var menus = []
var obrMenu = {name: 'obrMenu', menuItems: []};
obrMenu['menuItems'].push({name: "Alert", func: "alert('Success')"});
menus.push(obrMenu);
return menus;
}
Then within the container scripts use the following to translate this into something usable to create the menus with.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menus = lib.getMenu();
for (var i = 0; i < menus.length; i++) {
var cur = menus[i];
var items = cur['menuItems'];
var menuItems = [];
for (var j = 0; j < items.length; j++) {
var curFunc = new Function(
"return function " + items[j]['name'] + "(){" + items[j]['func'] + "}"
)();
menuItems.push({name: items[j]['name'], funcName: curFunc.name});
}
ss.addMenu(cur['name'], menuItems);
}
}
This method when ran, produces the error
Invalid argument: subMenus (line 15, file "Code")
with subMenus being the Apps Script argument name for what I have called menuItems. Whilst I gather this issue is probably down to the scoping of the produced functions, I can not seem to see how to get round it.
Any suggestions would be greatly appreciated. Many thanks.
Fix this line
menuItems.push({name: items[j]['name'], functionName: curFunc.name});
Using 'funcName' instead of 'functionName' as defined in GAS documentation is what messes it up. Apparently, the submenu object property names can't be changed.
I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:
<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
<select size="10" id="userChoice">
<? for (var i = 0; i < data.length; i++) { ?>
<option>
<?= data[i] ?>
<? } ?>
</select>
This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.
I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):
//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};
//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;
//array stringified
var dates = JSON.stringify(date);//Convert object to string
google.script.run
.getData2(dates);
Then here is the code that filters through the database on the server side:
function getData2(dates) {
var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
var date = JSON.parse(dates);
var dateArray = [];
for (var k in date) {//Loop through every property in the object
var thisValue = date[k];//
dateArray.push(thisValue);
};
var startDate = Date.parse(dateArray[0]);
var endDate = Date.parse(dateArray[1]);
var jobReference = [];
var job;
var dateCell1;
var dateCell;
if ((startDate==NaN) || (endDate==NaN)){
for (var i = 2; job!=""; i++){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
};
}
else{
for (var i = 2; job!=""; i++){
dateCell1 = ss.getRange(i,3).getValue();
dateCell = Date.parse(dateCell1);
if (startDate<=dateCell&&endDate>=dateCell){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
Logger.log("here it is"+jobReference);
}
else{
}
}
};
var jR = JSON.stringify(jobReference);
return jR;
}
Now I've tried several things, having a success handler change the line <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.
I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.
So the first bit of code on the client side for the select box I left the same.
The next bit, where I send the dates over to the server side was changed to this:
function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;
google.script.run.withSuccessHandler(dateSuccess)
.getData2(sdate,edate);
}
So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.
The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last. This kept the code from timing out on me.
Next I added the function I used for the success handler:
function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;
var data = JSON.parse(jobs)
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);
}
}
Works like a charm!
Scriptlets i.e. <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this
Firstly you set your google.script to call modifyoptions function on success
google.script.run.withSuccessHandler(modifyOptions)
.getData2(dates);
The above will code will automatically pass the return value of getData2 i.e Jr value to modifyOptions function
function modifyOptions(jobReference){
var selOpt = document.getElementById("userChoice")
selOpt.innerHTML ="" // Remove previous options
var options = ""
var data = JSON.parse(jobReference)
for (var i = 0; i < data.length; i++) {
options += "<option>"+data[i] +</option> //New string of options based on returned data
}
selOpt.innerHTML = options //Set new options
}
You can find a working example of how to modify the select-options in javascript here
Hope that helps!