dzisner
dzisner

Reputation: 315

Google Forms - get multiple choice response's index

I have a Google Form with several multiple choice questions which have textual answers. I can loop all questions in the form and get the text values of the answer using:

for(var i in headers) {
  message += e.namedValues[headers[i]].toString() + "\n\n"; 
}

However, I would also like to retrieve the index of each selected answer in order to provide a score.

Just to be clear - if I have the following multiple choice question in my form:

What is the airspeed velocity of an unladen swallow?

With the answers being:

If the submitter answered 'European or African?' I would like to get the index of that response - namely the number 2.

Thanks!

Upvotes: 1

Views: 3625

Answers (2)

Antonio Ooi
Antonio Ooi

Reputation: 1828

The MultipleChoiceItem.getIndex() method is still getting the index of the multiple choice question item, not the selected index of the multiple-choice response. To get the index of the selected choice, use MultipleChoiceItem.getChoices(), then loop through the choices[] array to compare the selected choice with each value of the choices[] array. If the choice value = selected choice, get the index of the array as the selected choice index:

// Add this function to 'on form submit' trigger.
function onFormSubmit(e) {
  var selectChoiceIndex = getSelectedChoiceIndex(e);
}

function getSelectedChoiceIndex(e) {
  var form = FormApp.getActiveForm();
  var mChoiceIndex = 1; // Assuming 1 is your mutiple-choice question index.
  var formResponse = e.response;
  var itemResponses = formResponse.getItemResponses();

  var selectedChoice = itemResponses[mChoiceIndex].getResponse();
  var choices = form.getItems(FormApp.ItemType.MULTIPLE_CHOICE)[mChoiceIndex].asMultipleChoiceItem().getChoices();

  for (i = 0; i < choices.length; i++) {
    if (selectedChoice == choices[i]) {
      return i;
    };
  }
}

Things to note:

  1. Example given in this answer is just a concept, not an optimized or fully tested version of the code.
  2. mChoiceIndex here is the index of the same ItemType on the form. It follows the sequence of how they're presented during run-time, not design-time, especially when you have conditional page-break/section.

Upvotes: 0

Related Questions