I am trying to create radio checkboxes, i managed to make it work when the checkboxes are in vertical as shown in the exemple sheet bellow with the tab name 'Radio 1' but i have another tab 'Radio 2' where the checkboxes are aligned horizontally and are not aligned one after the other but after every 2 cells, the first Radio works with the following code
function onEdit(e) {
if (e.range.columnStart != 2 || e.range.rowStart == 1 || e.range.rowStart > 8 || e.value != "TRUE") return;
let r = SpreadsheetApp.getActive().getActiveSheet().getRange(2,2,7);
let checks = r.getValues();
for (let i in checks){
if(checks[i][0] == true && i != e.range.rowStart - 2)
checks[i][0] = false;
}
r.setValues(checks);
}
but i cant make it to work when adapting to the second radio tab, any ideas?
CodePudding user response:
Try
function onEdit(e) {
var sh = e.source.getActiveSheet()
if (sh.getName() == 'Radio 1') {
if (e.range.columnStart != 2 || e.range.rowStart == 1 || e.range.rowStart > 8 || e.value != "TRUE") return;
let r = SpreadsheetApp.getActive().getActiveSheet().getRange(2, 2, 7);
let checks = r.getValues();
for (let i in checks) {
if (checks[i][0] == true && i != e.range.rowStart - 2)
checks[i][0] = false;
}
r.setValues(checks);
}
else if (sh.getName() == 'Radio 2') {
var cel = e.source.getActiveRange()
if (cel.getRow() == 11 && cel.getValue() == true) {
var r = sh.getRange('H' cel.getRow() ':S' cel.getRow())
var checks = r.getValues()
for (var i=0;i<checks[0].length;i =2) {
if (checks[0][i] == true && i != cel.getColumn()-8)
if (checks[0][i]==true) {checks[0][i] = false};
}
r.setValues(checks);
}
}
}
If you want to apply to multi-rows, change this cel.getRow() == 11
CodePudding user response:
In your situation, how about the following modification?
Modified script:
In this modification, the cell ranges of checkboxes are used.
function onEdit(e) {
// This is from your sample Spreadsheet.
// The cell ranges of checkboxes are set as A1Notation.
const obj = {
'Radio 1': ["B2", "B3", "B4", "B5", "B6", "B7", "B8"],
'Radio 2': ["H11", "J11", "L11", "N11", "P11", "R11"]
};
const sheet = e.source.getActiveSheet();
const sheetName = sheet.getSheetName();
const a1Notation = e.range.getA1Notation();
if (!obj[sheetName] || !obj[sheetName].includes(a1Notation) || e.range.getValue() === false) return;
sheet.getRangeList(obj[sheetName].filter(e => e != a1Notation)).uncheck();
}
- When this script is run, when a checkbox is checked on "Radio 1" or "Radio 2", other checked checkboxes are unchecked.
- If you want to add "Radio 3" and others, please add them to
obj
.
Note:
- When you changed the checkboxes and the sheet names, please modify
obj
. Please be careful about this.