简体   繁体   中英

How can I add choices in a Google Form with Google Apps Script

I'm trying to master creating Google Forms programmatically, but can't assign choices to a multiple-choice item. I can create the item (testQuestion) and give it a title, but my createChoice() statements don't add choices.

Here's my code, based on https://developers.google.com/apps-script/reference/forms/page-navigation-type

function testCreateChoices() {

/* modification of
  testPageNavigation()
  to see how to import choices from a range on sheet
*/

// Create a form 
var form = FormApp.create('createChoice Test');

// add a multiple-choice item
var testQuestion = form.addMultipleChoiceItem();
testQuestion.setTitle('Anything here?');
var whatsis = testQuestion.createChoice('bozzle');
var firstChoice = testQuestion.createChoice('this');
testQuestion.createChoice("that");
testQuestion.createChoice("the other");
testQuestion.createChoice("Ouch!");


//add a new multiple-choice item and a pagebreak item
var item = form.addMultipleChoiceItem();
var pageBreak = form.addPageBreakItem();

// Set some choices with go-to-page logic.
var rightChoice = item.createChoice('Vanilla', FormApp.PageNavigationType.SUBMIT);
var wrongChoice = item.createChoice('Chocolate', FormApp.PageNavigationType.RESTART);

// For GO_TO_PAGE, just pass in the page break item. For CONTINUE (normally the default), pass in
// CONTINUE explicitly because page navigation cannot be mixed with non-navigation choices.
var iffyChoice = item.createChoice('Peanut', pageBreak);
var otherChoice = item.createChoice('Strawberry', FormApp.PageNavigatio[enter image description here][1]nType.CONTINUE);
item.setChoices([rightChoice, wrongChoice, iffyChoice, otherChoice]);
  
}

Here's what I get, with the choices "bozzle" and so on not displayed, and an image of what I want but can't create.

Many thanks for any help!

Here's a screenshot, with no labels/choices under "Anything here?"

And a mockup with "bozzle", "this" and so on as choices

The reason you are not seeing the options for the testQuestion is because you didn't set the choices for the question.

Therefore, I suggest you update the bit where you create your first question to this:

var testQuestion = form.addMultipleChoiceItem();
testQuestion.setChoices([testQuestion.createChoice('bozzle'), testQuestion.createChoice('this'), testQuestion.createChoice("that"), testQuestion.createChoice("the other"), testQuestion.createChoice("Ouch!")]);

The createChoice method is used to create the choice items only and in order to actually add them to the question, you have to use the setChoices method as well.

Reference

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