Last active
September 18, 2023 19:45
-
-
Save sanbornick/b6c002d368913594bae6da664d4b193c to your computer and use it in GitHub Desktop.
Dynamic list options in Google Forms.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Any option added in other by a user who submits the form is then avaialbe in the explicit options for other users. | |
//This by default acts on all checkbox and multiple choice responses in the form. Make sure each has at least one option | |
//other than "other" to begin with or else you're gonna have a bad time. | |
function onSubmit(e) { | |
var formResponse = e.response; | |
var itemResponses = formResponse.getItemResponses(); | |
var item, itemAsItemType, choices, choicesStrings, io, response, a, b; | |
for (a = 0; a < itemResponses.length; a++) { | |
response = itemResponses[a].getResponse(); | |
if (response === '') { | |
//bogey, bail | |
Logger.log('Empty Response, something wrong here.'); | |
return; | |
} | |
item = itemResponses[a].getItem(); | |
switch (item.getType()) { | |
case FormApp.ItemType.CHECKBOX: | |
itemAsItemType = item.asCheckboxItem(); | |
break; | |
case FormApp.ItemType.MULTIPLE_CHOICE: | |
itemAsItemType = item.asMultipleChoiceItem(); | |
break; | |
default: | |
return; | |
} | |
choices = itemAsItemType.getChoices(); | |
choicesStrings = []; | |
for (b = 0; b < choices.length; b++) { | |
choicesStrings[b] = choices[b].getValue(); | |
} | |
if (Array.isArray(response)) { | |
for (b = 0; b < response.length; b++) { | |
io = choicesStrings.indexOf(response[b]); | |
if (io === -1) { | |
Logger.log('Missing choice "%s". Adding to available choices.', response[b]); | |
choicesStrings.push(response[b]); | |
} | |
} | |
} else { | |
io = choicesStrings.indexOf(response); | |
if (io === -1) { | |
console.log('Missing choice "%s". Adding to available choices.', response); | |
choicesStrings.push(response); | |
} | |
} | |
//need to clear 'other' option before setting choices or it will throw an error. | |
//Also can't clear other option if form has no current options so if you don't | |
//seed the question with at least one option the item will be caught in a position | |
//that cannot be corrected by code and only through the editor web interface. | |
itemAsItemType.showOtherOption(false); | |
itemAsItemType.setChoiceValues(choicesStrings); | |
itemAsItemType.showOtherOption(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment