Search code examples
javascriptgoogle-apps-scriptgoogle-sheetscheckbox

How to check a checkbox in Google Apps Script and uncheck all the other cells?


So I'm trying to make a sign-in/sign-up form on Google Sheets, and I have two checkboxes, one that says login, and one with sign up. In my apps script, I'm trying to make it so that only one of them can be checked. This is my code, and it's not working. Help?

function signupLogin() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  if (sheet.getRange('A13').isChecked() === 'TRUE') {
    sheet.getRange('B13').setValue('FALSE');
  } else {
    sheet.getRange('B13').setValue('TRUE'); 
  }
}

The code will always make the second checkbox ticked, even if the first one is ticked.


Solution

  • When you check A13 or B13 the other cell will be unchecked automatically.

    Therefore, I think an onEdit() solution is what you are looking for:

    function onEdit(e) {
      
      const as = e.source.getActiveSheet();
      const cell = e.range.getA1Notation();
      const cell_checks = ['A13','B13'];
      if(as.getName() == "Sheet1" && cell_checks.includes(cell) && e.range.isChecked())
      {cell_checks.filter(val=>val!=cell).forEach(c=>as.getRange(c).uncheck())}  
    }
    

    To use this solution, just save the aforementioned code to the script editor and then every time you click on the checkbox in Sheet1 (modify the name to your needs) the rest checkboxes will be unchecked.

    This code is also scalable. Namely, if you want to have multiple checkboxes and when you click one of them, the rest become unchecked. You can define the list of your checkboxes here:

     const cell_checks = ['A13','B13'];