Creating Quizzes in Google Form using Google Forms Service with Google Apps Script

Gists

Creating Quizzes in Google Form using Google Forms Service with Google Apps Script

This is a sample script for creating quizzes in Google Form using Google Forms Service with Google Apps Script.

Usage

1. Prepare questions and answers.

In this sample, the questions and answers are prepared using Spreadsheet as follows.

Creating Quizzes in Google Form using Google Forms Service with Google Apps Script

2. Sample script.

This script is container-bound script of the above Spreadsheet.

function myFunction() {
  const formTitle = "sample"; // This is a form title.
  const sheetName = "Sheet1"; // This is a sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const [, ...values] = sheet
    .getDataRange()
    .getDisplayValues()
    .filter((r) => r.join("") != "");
  const obj = values.map(([a, b, c]) => {
    const answers = b
      .split("\n")
      .map((e) => e.trim())
      .filter(String);
    const correct = c
      .split("\n")
      .map((e) => e.trim())
      .filter(String);
    return {
      question: a,
      answers,
      correct,
      point: 1,
      type: correct.length == 1 ? "addMultipleChoiceItem" : "addCheckboxItem",
    };
  });
  const form = FormApp.create(formTitle)
    .setIsQuiz(true)
    .setTitle("Sample questions");
  obj.forEach(({ question, answers, correct, point, type }) => {
    const choice = form[type]();
    const choices = answers.map((e) =>
      choice.createChoice(e, correct.includes(e) ? true : false)
    );
    choice.setTitle(question).setPoints(point).setChoices(choices);
  });
}

Note

 Share!