I am working in Google Apps Script with the purpose of creating a spreadsheet. I create an html form with checkboxes defined by an array. The actual array is retrieved from a spreadsheet, but this will demonstrate problem.
Assignment.html
<!DOCTYPE html>
<html>
<body>
<form id="assignmentForm" onSubmit="google.script.run.withSuccessHandler(google.script.host.close).handleForm(this);">
<p><label for="name">Assignment Name:</label>
<input type="text" id="name" name="name"></p>
<? var standards = ["1A", "1B", "2C"]; ?>
<? for( var i = 0; i < standards.length; i = i + 1) { ?>
<p>
<input type="checkbox" id="<?= standards[i] ?>" name="<?= standards[i] ?>" value="<?= standards[i] ?>">
<label for="<?= standards[i] ?>"> <?= standards[i] ?> </label>
</p>
<? } ?>
<input type="submit" value="Submit">
</form>
</body>
</html>
I activate the form
function createAssignment() {
try {
html = HtmlService.createTemplateFromFile('Assignment.html').evaluate();
SpreadsheetApp.getUi().showModalDialog(html, 'Create Assignment');
} catch (e) {
console.log('Failed with error: %s', e.error);
}
return;
}
I then retrieve the results in app script.
function handleForm(data){
Logger.log(data);
Logger.log(data.name);
var checked = getCheckedFieldsAsArray(data);
doUsefulStuff(checked);
}
I can get the name because I know that field name. I don’t know what is in the array (or how many items) at code time so I don’t know how to access what boxes were checked with data.____. I do have access to the standards array at run time. I would like an array of all the names of the checkboxes that were checked.
2
Answers
Reccomendation:
One workaround is to compare the object properties (in other words, the form responses) to an array of all of the possible field names of the checkboxes. Using your example, I’ve modified your script to this:
References:
Object.getOwnPropertyNames()
forEach()
Let me suggest the following changes to your project:
For my testing I have in Code.gs. When I check some boxes and click submit.
Code.gs
Execution log