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

冷暖自知 提交于 2021-02-10 08:34:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!