问题
Say I have a list of 1000 animals in a Google Sheet (e.g., dog, cat, cow, ..., giraffe). I'll like the Google Form to randomly pick one of these animals every time a respondent opens the Form.
E.g., Have you ever seen a __________ ?
Here, the blank would be different for every respondent (unless they were lucky enough to randomly get matching animals).
I currently have the code to randomly select an animal from the Google Sheet, but I can't figure out how to randomly select an animal for each respondent, since the onOpen() function cannot trigger for every respondent, but only when the owner opens the Form.
function onOpen(e){
var animals = worksheet.getRange(2, 1, worksheet.getLastRow()-1, 1)
.getValues()
.map(function(o){ return o[0]})
.filter(function(o){return o !== ""});
//Logger.log(animals)
// get random animal
var animal = animals[Math.floor(Math.random()*animals.length)];
Logger.log(animal);
var id = getBlockIdFromTitle()
Logger.log(id)
if (id !== -1){
updateLink(id, animal)
}
}
Any advice on how to change my code or do a completely different approach to achieve the same results will be appreciated. Thanks!
回答1:
Instead of onOpen
trigger, use the installable onFormSubmit
trigger
This will allow you to update your form question after a respondent has submitted the form.
Sample:
function onFormSubmit(e){
var animals = worksheet.getRange(2, 1, worksheet.getLastRow()-1, 1)
.getValues()
.map(function(o){ return o[0]})
.filter(function(o){return o !== ""});
//Logger.log(animals)
// get random animal
var animal = animals[Math.floor(Math.random()*animals.length)];
FormApp.openById("XXX").getItems()[0].asTextItem().setTitle("Have you ever seen a " + animal + "?");
}
}
Mind:
Since the question will only be updated on form submit, the respondents that will open the form before the preceding respondent finishes submitting will not see a different version of the form.
However, currently there is no other option to change the question contents dynamically for each respondent.
If it is helpful for your - there options to shuffle question order and answer options to different respondents.
来源:https://stackoverflow.com/questions/60910988/can-i-use-google-apps-script-to-make-a-google-form-display-randomized-text-from