简体   繁体   中英

Can I use Google Apps Script to make a Google Form display randomized text from a Google Sheet?

Say I have a list of 1000 animals in a Google Sheet (eg, dog, cat, cow, ..., giraffe). I'll like the Google Form to randomly pick one of these animals every time a respondent opens the Form.

Eg, 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM