Search code examples
google-apps-scriptgmail-addons

How to tell if SelectionInput checkbox is checked or not in callback?


How can you tell if a SelectionInput checkbox item is checked in a callback? I have the following:

section.addWidget(CardService.newSelectionInput()
                .setType(CardService.SelectionInputType.CHECK_BOX)
                .setFieldName("chkSaveAttachments")
                .addItem("Save Attachments", "chkSaveAttachmentsValue", true));

I have a button on my card that triggers a callback. From the callback, all I can access is the value ("chkSaveAttachmentsValue") but I can't tell whether the box is checked or unchecked.

function saveCallback(e) {
  Logger.log(e.formInput.chkSaveAttachments); //prints "chkSaveAttachmentsValue"
  Logger.log(e.formInput.chkSaveAttachments.chkSaveAttachmentsValue) //undefined
  Logger.log(e.formInput.chkSaveAttachments.chkSaveAttachmentsValue.selected) //undefined
}

Solution

  • You can get the state of checkbox by looking at the formInput in the onChange callback.

    CardService.newSelectionInput()
                .setType(CardService.SelectionInputType.CHECK_BOX)
                .setFieldName("chkSaveAttachments")
                .addItem("Save Attachments", "chkSaveAttachmentsValue", true).setOnChangeAction(selectionAction)
    
    var selectionAction = CardService.newAction().setFunctionName("selectionAction").setParameters({"obj": obj});
    
    function selectionAction(e) {
        //formInput value comes only when it is selected.
        var selected = !!e.formInput.chkSaveAttachments;
        // you can set and access paramters in the onchange action for further use.
        if(selected) {
        // cache the state using cacheservice
        } else {
        // cache the state using cacheservice
        }
    }