3
votes

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.

4
Explain "it's not working."TheMaster
@TheMaster The code will always make the second checkbox ticked, even if the first one is ticked.EnderCodesLol

4 Answers

4
votes

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'];
4
votes

Issue:

if (sheet.getRange('A13').isChecked() === 'TRUE') {

If the operands are of different types, return false

Solution:

  • Use strict comparison with literal Boolean true

    if (sheet.getRange('A13').isChecked() === true) {
    
  • Or if null is NOT expected, Use the returned Boolean directly in if's condition:

    if (sheet.getRange('A13').isChecked()) {
    
1
votes

To the question "How to check a checkbox in Google Apps Script?":

SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName('sheetName')
  .getRange('D5')
  .check();
1
votes

You are literally comparing Boolean result of enter code here sheet.getRange('A13').isChecked() to the string literal which results in always false expression. Simply check the boolean:

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