Generate random values and print them in Google Form

Viewed 4962

I am creating a google form where I have three sets of values and I want to randomly select one value from all the three sets and print them as a question.

The extension of the script is ".gs"

I tried using RANDBETWEEN(low, high) but the script throws an error. Seems like this is for google sheets.

Requesting for some help on how to create one.

enter image description here

2 Answers

For you random number, you'll need to use the Math library:

var nums = Math.floor(Math.random() * 4) + 1;

That should give you a random number between 1 and 5.

Seems like a little bit of confusion here:

  • RANDBETWEEN(low, high) is a special Google Spreadsheet function.
  • Inside a Google Script, you must use plain JavaScript (plus a few custom Google functions, like the FormApp.create() function you're using.)

In JavaScript, Math.random() is a way of getting a (pseudo) random number, but it returns a float between 0 and 1. To convert that into an integer in a range we have to use a bit of math. It might be helpful to define your own getRandomInt function, like this:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

Then later on you could call getRandomInt(5), returning 0, 1, 2, 3, or 4.

Related