Search code examples
google-apps-scriptgoogle-forms

How can i set the correct answer to a multiple choice question with AppScript?


i am trying to add the question correct answer to my form.

  //question1
   var Title = setupSheet.getRange('B1').getValue(); 
     if( Title != "" ){
      form.addMultipleChoiceItem()
      .setTitle(setupSheet.getRange('B1').getValue())
      .setChoiceValues(setupSheet.getRange(2,2,setupSheet.getLastRow()-1,1).getValues());
  }
  else {}

Solution

  • The only way to set the choices with the correct option/s included is with the setChoices() function. For this you have to create an array of "Choice" objects.

    Assuming "form" is a Form object and you obtain the data from the B column (1st row for the title and the rest for the options), i tweaked your code to add the question with the correct answers using the "correct" array, in this case it'll create a question with the option 3 and 5 as correct.

     var Title = setupSheet.getRange('B1').getValue();
      if( Title != "" ){
        var question = form.addMultipleChoiceItem()
        .setTitle(setupSheet.getRange('B1').getValue())
    
        var choices = setupSheet.getRange(2,2,setupSheet.getLastRow()-1,1).getValues();
        var correct = [false, false, true, false, true];
        var choicesArr = [];
    
        for (var i=0; i<choices.length; i++) {
          var choice = choices[i][0];
          choicesArr.push(question.createChoice(choice, correct[i]));
        }
    
        question.setChoices(choicesArr);
      }
    

    Also, bear in mind that the correct answers feature is present only for forms with the "quiz" option activated.