Dynamic Google Form using Google Apps Script - javascript

I have set up an item on my Google Form to set list based on values from a Google spreadsheet, code is:
function updateForm(){
var form = FormApp.openById("FormID");
var namesList = form.getItemById("ItemID").asListItem();
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("SourceSheetName");
var namesValues = names.getRange(2, 1, names.getMaxRows() - 1).getValues();
var List = [];
for(var i = 0; i < namesValues.length; i++)
if(namesValues[i][0] != "")
List[i] = namesValues[i][0];
namesList.setChoiceValues(List);
}
This works perfectly fine.
What I really want is to set each of the items listed on a spreadsheet to take you to a specific section on the Google Form.
I know this can be done manually on the Google Form by using 'Go To Section Based On Answer', but I was wondering if I can add a second column on the source spreadsheet to list the sections and amend my code accordingly?
EDIT - this is not a duplicate to another question which is mentioned below. The question asked previously had 2x choices set in the code. My question involves a set of responses set in a Googlesheet that auto populates the Google Form. What I really want is to auto set Go To Section Based on Answer automatically too. I hope this makes sense. Thanks

Related

Data Validation from another Spreadsheet Range

I have a spreahsheet A on Googlesheet with a range, list of cities for example.
I have a spreadsheet B on Googlesheet where I'd like to use Data Validation validating from the other file.
Goal
The purpose is to 'hide' or make it less available, if I use protect/hide any download to Excel removes the protection and it's not really protected.
I thought I could use a custom function to set dataValidation and it works but if I add a city in spreadsheet A it's not reflected in the previous cells.
Option 1
This works but the validation rule is not refreshed
var sheetA = SpreadsheetApp.openById("spread-a").getSheetByName("Data");
var currentSpreadsheet = SpreadsheetApp.getActive();
var rule = SpreadsheetApp.newDataValidation().requireValueInList(dataSheet.getRange('Cities').getValues()).build();
getActiveSpreadsheet().getActiveCell().setDataValidation(rule);
Option 2
Custom function doesn't work
*using it as Formula *=getList('Cities')**
function getList(name) {
var cell = SpreadsheetApp.getActiveSpreadsheet().getActiveCell();
var rule = SpreadsheetApp.newDataValidation().requireValueInList(dataSheet.getRange(name).getValues()).build();
cell.setDataValidation(rule);
return cell
}

Get random range google spreadsheet

I have managed with VBA and Excel to achieve my purposes, but I'd like to move to google spreadsheet for particular reasons.
I'm trying to replicate a code that works just fine in VBA.
It's simple, I have a sheet with a bank of questions in column A, and I'd like a macro that can select 1 random question and copy it to a second sheet.
I'm having trouble understanding how I can access a random cell, copy it and paste it to the second sheet. Some plain explanation would be appreciated since I have very little or non-existent knowledge of programming or javascript.
function test() {
var ss = SpreadsheetApp.openById("sheetID");
//Say I have 10 questions in the BANKSHEET, for instance
var rQuestion = Math.floor(Math.random()*10+1);
//What goes in A1? So that I can access the range randomly according to rQuestion value.
var inputRange = ss.getSheetByName("BANKSHEET").getRange("A1");
var inputValues = inputRange.getValues();
var outputRange = ss.getSheetByName("QUIZZ").getRange("A1").setValues(inputValues);
How about this modification? I think that there are several solutions for your situation. So please think of this as one of them.
Modification points :
Retrieve the number of cells at "A1:A" from sheet of "BANKSHEET".
Retrieve randomly one of the number.
Copy the cell value of the retrieved number to "A1" of "QUIZZ".
Modified script :
function test() {
var ss = SpreadsheetApp.openById("sheetID");
// Retrieve randomly a value from sheet of BANKSHEET
var sheet = ss.getSheetByName("BANKSHEET");
var src = sheet.getRange("A" + (1 + Math.floor(Math.random() * sheet.getLastRow())));
// Put the value to "A1" at sheet of QUIZZ
var dst = ss.getSheetByName("QUIZZ").getRange("A1");
src.copyTo(dst);
}
Note :
It supposes that there are values in only column A of "BANKSHEET".
This modified script randomly retrieves one value from column A of "BANKSHEET" every time.
If you don't want to use the value which has already been used, please modify the script for your situation.
Reference :
copyTo()
If I misunderstand your question, I'm sorry.

Looping through cells in Google Spreadsheet

I've been busy trying to use the build-in javascript in Google Spreadsheet, however, not having worked in either javascript or Google Spreadsheet, i'm having a few difficulties.
My script is supposed to read a number (1-3) in a cell, and from that number parse an image to the cell below (I've been using the setFormula command for this).
So far it's working for 1 cell (B6 as i've choosen right now), but i would like to loop through a column with numbers in every other cell (So that after the script has run, it's number-picture-number-picture etc) - i just can't figure out how.
The code i'm using right now:
function numbtoimage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var url = 'IMAGE("https://dl.dropboxusercontent.com/s/bpqy8o796casqjl/belt.JPG?dl=0", 2)';
var url2 = 'IMAGE("https://dl.dropboxusercontent.com/s/4q8sakhkpot0h65/belt2.JPG?dl=0",2)';
var url3 = 'IMAGE("https://dl.dropboxusercontent.com/s/kvsf4z6z45rcg53/belt3.JPG?dl=0",2)';
var cell = sheet.getRange("B6")
var data = cell.getValue()
if(data==1) {cell.offset(1, 0, 1).setFormula(url);}
else if(data==2) {cell.offset(1, 0, 1).setFormula(url2);}
else if(data==3) {cell.offset(1, 0, 1).setFormula(url3);}
}
I've looked at This similar problem, but have been unable to make it work for my case.
Any help is greatly and truly appreciated!
Nicklas
You need some sort of loop to go through the data. I Would suggest a FOR loop.
Your script is currently written to get one single cell value, rather than all the values.
So it might be an idea to get all values in one go, then check whats in them.
Also from you question, it's not clear where the numbers will be found.
Only in column B?
Here is a quick example (untested), that goes through column B looking for a number and it should insert the link in the cell below based on that number. This code is based on your original example and untested but hopefully it helps.
function numbtoimage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var url = 'IMAGE("https://dl.dropboxusercontent.com/s/bpqy8o796casqjl/belt.JPG?dl=0", 2)';
var url2 = 'IMAGE("https://dl.dropboxusercontent.com/s/4q8sakhkpot0h65/belt2.JPG?dl=0",2)';
var url3 = 'IMAGE("https://dl.dropboxusercontent.com/s/kvsf4z6z45rcg53/belt3.JPG?dl=0",2)';
var values = sheet.getValues();
for(i=0; i < values.lenth ; i++){
if(values[i][1]==1) {sheet.getRange(i+2, 2).setFormula(url);}
else if(values[i][1]==2) {sheet.getRange(i+2, 2).setFormula(url2);}
else if(values[i][1]==3) {sheet.getRange(i+2, 2).setFormula(url3);}
}
}

Google Spreadsheet Determine lowest number in a row of cells

I'm new to this site for the main purpose that I plan to pursue a career in programming. I've landed my first job at an engineering company who is asking me to set up a system in which they can easily determine the time between a job being filed, and it's completion. We're using spreadsheet docs right now to accomplish certain pieces of this.
I'm looking to create a custom function in Google Docs that will allow me to traverse the array of values in row C and then compare it with a number that the function was called with, compare the number to the number in the array and give me which one is the smaller number. EDIT: The function will be called on another sheet called "parsed data" located in the same project file. It's purpose is to automatically file the order number of a current project (just for the sake of being organized) All the other functions I plan to implement will be based off of this order number being correct.
So far, I've gathered this much (I'm learning this on the fly because I still lack experience, so bear with me.)
{
/**created by Alexander Bickford for use at Double E Company
*sorts through a range of values to determine the lowest next value
*returns lowest determined value of next cell
*/
//List Of To Be Implemented Functions
// sheet.appendRow
function setValue(num)
{
var ss = SpreadsheetApp.getActiveSpreadsheet('parsed data');
var ss = ss.getSheets()[0];
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange;i++) //Loop to traverse the C range and find the lowest value.
{
if(num<=range[3][i])
{
}
else
num = range[3][i];
}
return num;
}
}
when I call the function in the spreadsheet, I'm getting an error passed that says:
error: ReferenceError: "SPREADSHEET_ID_GOES_HERE" is not defined. (line 8, file "Code")
Google predefines some functions at the top that look like this:
/**
* Retrieves all the rows in the active spreadsheet that contain data and logs the
* values for each row.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function readRows() { <---Line 8 in the file
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
End Code I don't need */
I assume it has something to do with the earlier lines (I pointed out line 8). Any thoughts?
Below code is working fine for me.
var ss = SpreadsheetApp.getActiveSheet();
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange.length;i++)
{
Logger.log(myRange[i]);
}
Looking at your code, it seems like you have a few problems.
You seem to be mixing up "sheets" with "spreadsheet", and your redundant declaration of "ss" as a variable is bound to cause you some problems.
You seem to be passing in arguments to the incorrect methods. I had this same problem when working with the Google App script earlier. It took a lot of poking around Google's Documentation (which you should really take a look at: https://developers.google.com/apps-script/). You seem to be making the same mistake I did, coding by analogy. looking at Google's sample code and trying to replicate is bound to bump you into some trouble.
Some useful advice:
The most confusing thing to wrap your head around is the structure: spreadsheet>>sheet>>range, you have to explicitely deal with the one's on top before moving to the one's on the bottom.
Remove the 'parsed data' argument from getActiveSpreadsheet(), it should be blank. What you want to use is "getSheetByName("parsed data")" and pass that into a sheet variable.
In your for loop, you also need to use the ".length" method, or use the ".getLastRow()" method with a sheet object to find the last row in your sheet.
Your code might look something like this:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("parsed data");
var endRowNumber = sheet1.getLastRow();
//insert rest of code

Dropdown Menu using the 'storeLocator.Feature' in the Store Locator Library for Maps API

Is there any way of using a Dropdown Menu as opposed to the checkbox's that are used in the examples of the Store Locator Library for Maps API. The checkbox is a 'storeLocator.Feature' item.
Essentially I want the user to be able to select an item from the dropdown list and this instantly change the markers on the map.
I am very new to Javascript coding but experienced in CSS, HTML and other computer languages. I have followed the examples in the link fairly closely so you can assume my own code looks the same. –
Here is the section of code i think i have to edit:
DataSource.prototype.parse_ = function(csv) {
var stores = [];
var rows = csv.split('\n');
var headings = this.parseRow_(rows[0]);
for (var i = 1, row; row = rows[i]; i++) {
row = this.toObject_(headings, this.parseRow_(row));
var features = new storeLocator.FeatureSet;
features.add(this.FEATURES_.getById('Cafe-' + row.Cafe));
features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair));
features.add(this.FEATURES_.getById('Audio-' + row.Audio));
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', ');
var locality = this.join_([row.Locality, row.Postcode], ', ');
var store = new storeLocator.Store(row.uuid, position, features, {
title: row.Fcilty_nam,
address: this.join_([shop, row.Street_add, locality], '<br>'),
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
Thanks.
you need to follow these steps:
set the featureFilter-option of the panel to false
(this will prevent the library from creating the checkboxes)
create a variable where you store all features for later use:
var features=view.getFeatures().asList();
this returns an array with all features
create the select-element
populate the select-element with the needed option-elements
iterate over the features-array created above and append an option for every item to the select .
The text to display inside the option you get by calling the getDisplayName()-method of the item.
add a change-handler to the select with the following callback:
function(){
view.set('featureFilter',
new storeLocator.FeatureSet(features[this.selectedIndex]));
view.refreshView();}
(where view is the storeLocator.View and features the array created in step#2)
5. put the select to the desired place inside the document
Hope i'm allowed to comment here as i found this question very useful for my implementation of store locator.
Dr Molle's solution in the JS fiddle is excellent however i've just noticed that the 'directions' functionality of the map no longer works. Could this easily be rectified? thanks
edit: easier than i thought. In the fiddle "featureFilter:" is set to 'false'. A div with the class="feature-filter" needs to be present in the code for the directions to appear, setting the value to 'true' shows the div (and checkboxes) so that directions work. Checkboxes were hidden in the stylesheet..
.storelocator-panel .feature-filter {
/*overflow: hidden;*/ display:none
}
This may be useful to someone

Categories

Resources