Reputation: 41
I'm new to Google Apps Script and I'm currently working on a project where I need to select all the checkboxes in a Google Doc using Google Apps Script, with the goal of determining if they've been checked or not, I will use this information to populate an external database. However, most of the solutions I've found are related to Google Sheets, not Google Docs.
I've tried using the getListItems()
method to retrieve the list items in the document, hoping it would include the checkboxes as well. However, it seems to only select the bulleted points and not the checkboxes. When I run the code, I encounter the error "TypeError: Cannot read properties of null (reading 'toString')"
on the line where I try to access the getGlyphType()
.
Here's the code snippet I've tried:
function getCheckboxValue() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
const listItems = body.getListItems()
for(let item of listItems){
console.log(item.getGlyphType().toString())
}
}
and this is what gets returned
4:47:46 PM Notice Execution started
4:47:46 PM Info BULLET
4:47:46 PM Info BULLET
4:47:46 PM Info BULLET
4:47:46 PM Info BULLET
4:47:46 PM Info BULLET
4:47:47 PM Error
TypeError: Cannot read properties of null (reading 'toString')
getCheckboxValue @ Code.gs:8
I've also included an image of the document layout to provide a visual representation:
Is there a way to select all the checkboxes in a Google Docs document using Google Apps Script? If so, how can I modify my code to achieve this? Any guidance or alternative approaches would be greatly appreciated.
Upvotes: 3
Views: 917
Reputation: 38416
Using Class DocumentApp or the Advanced Docs Service from Google Apps Script is impossible to select a checkbox and get its checked/unchecked state.
As you have found, a checkbox (a checklist item) is an instance of Class ListItem. This class doesn't include a method to get or set an item as checked or unchecked checkboxes. The Enum GlyphType doesn't include a checkbox type.
Considering this, consider looking for another option to get the data that you need to send to your database.
Note: Using the Advanced Docs Service it's possible to convert a paragraph into checklist. For more details see my answer to How to add a checklist in Google Docs?
Upvotes: 1