Reputation: 315
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
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:
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
Reputation: 590
use class FormResponse (https://developers.google.com/apps-script/reference/forms/form-response)
and method ItemResponse.asMultipleChoiceItem (https://developers.google.com/apps-script/reference/forms/item#asMultipleChoiceItem())
and method MultipleChoiceItem.getIndex() (https://developers.google.com/apps-script/reference/forms/multiple-choice-item#getIndex())
Upvotes: 0