Script for Google Forms. Uses "Other" field in checkbox and radio groups to add options from responses.
/* | |
Script for Google Forms. | |
"Fixes" other... field in checkbox and radio groups. | |
Whenever form is submitted and "other" option is selected, | |
input goes to corresponding checkbox/radio group in form | |
as a new option, so next respondents don't have to put it | |
in manually. | |
To use copy-paste code to your forms project and assign | |
onSubmit function to project's "on form submit" trigger. | |
By default applies to all checkbox/radio groups in the | |
form, specify required IDs in applyOnlyTo if needed. | |
Normally it is in "data-item-id" field and numeric only. | |
E.g. data-item-id="193574675" | |
*/ | |
function onSubmit(event) { | |
var applyOnlyTo = []; // fill this in if you want descibed behaviour only for selected checkbox/radio groups; | |
var form = event.source; | |
var response= event.response; | |
var choosers; | |
if (applyOnlyTo.length > 0) { | |
choosers = applyOnlyTo.map(function(id) { | |
return form.getItemById(id); | |
}); | |
} else { | |
var checkboxes = form.getItems(FormApp.ItemType.CHECKBOX); | |
var radios = form.getItems(FormApp.ItemType.MULTIPLE_CHOICE); | |
choosers = checkboxes.concat(radios); | |
} | |
choosers.filter(function(c) { | |
var type = c.getType(); | |
return (type == FormApp.ItemType.CHECKBOX) ? c.asCheckboxItem().hasOtherOption(): | |
(type == FormApp.ItemType.MULTIPLE_CHOICE) ? c.asMultipleChoiceItem().hasOtherOption(): | |
false; | |
}); | |
for (var i = 0; i < choosers.length; i++) { | |
var chooser = choosers[i]; | |
chooser = (chooser.getType() == FormApp.ItemType.CHECKBOX) ? chooser.asCheckboxItem(): | |
(chooser.getType() == FormApp.ItemType.MULTIPLE_CHOICE) ? chooser.asMultipleChoiceItem(): | |
"Something went wrong. It is definitely Google's fault!"; | |
var chooserResponse = response.getResponseForItem(choosers[i]); | |
if (chooserResponse == null) continue; | |
chooserResponse = chooserResponse.getResponse(); | |
var otherField = (chooser.getType() == FormApp.ItemType.CHECKBOX)? | |
chooserResponse[chooserResponse.length-1]: | |
chooserResponse; | |
var choices = chooser.getChoices(); | |
if (!mContains(choices, otherField)) { | |
var newChoice = chooser.createChoice(otherField); | |
choices.push(newChoice); | |
chooser.setChoices(choices); | |
} | |
} | |
} | |
function mContains(choices, item) { | |
for (var i = 0; i < choices.length; i++) { | |
if (choices[i].getValue() == item) {return true;} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment