Issue
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.
Solution
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:
function handleForm(data) {
Logger.log(data);
Logger.log(data.name);
var checked = getCheckedFieldsAsArray(data);
checked.forEach(x => Logger.log(data[x])); // outputs the values of all of the checked fields for debugging. Feel free to remove this.
doUsefulStuff(checked);
}
function getCheckedFieldsAsArray(data) {
var standards = ["1A", "1B", "2C"]; //Array of all of the possible checkbox fields. This should match the array on Assignment.html
var checkedFields = [];
Object.getOwnPropertyNames(data).forEach(x => {
/*
Loops through all of the properties of the form response.
If there's a match, form response field is pushed to the checkedFields array
*/
if (standards.indexOf(x) != -1) checkedFields.push(x);
})
return checkedFields;
}
References:
Answered By - DuuEyn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.