xxxxxxxxxx
89
const options = ["option 1", "option 2", "option 3", "option 4"];
let radio;
function setup() {
createCanvas(400, 400);
radio = createRadio();
radio.position(10, 10);
radio.style("width: 80px; font-family: sans-serif");
options.forEach((v) => radio.option(v));
radio.selected = selectedFixed;
radio.selected("option 2"); // <--- can be any other option
// ====== Paul Wheeler's workaround for selected() ======
radio.selectedXXX = function (value) {
let self = this;
let result = null;
if (value === undefined) {
for (const option of self._getOptionsArray()) {
if (option.checked) {
result = option;
break;
}
}
} else {
// deselect all first (Google Chrome wigs out when multiple options have the checked attribute set to true)
self._getOptionsArray().forEach(option => {
option.checked = false;
option.removeAttribute("checked");
});
for (const option of self._getOptionsArray()) {
if (option.value === value) {
option.setAttribute("checked", true);
option.checked = true;
result = option;
break;
}
}
}
return result;
};
// ==============================================
let nextButton = createButton("Select Next Option");
nextButton.position(100, 10);
nextButton.mouseClicked(() => {
let ix = options.findIndex((opt) => opt === radio.value());
const opt = options[++ix % options.length];
radio.selected(opt);
console.log(radio._getOptionsArray());
});
}
function draw() {
background(255);
textSize(20);
text("button value: " + radio.value(), 40, 120);
}
function selectedFixed(value) {
let self = this;
let result = null;
if (value === undefined) {
for (const option of self._getOptionsArray()) {
if (option.checked) {
result = option;
break;
}
}
} else {
// deselect all first (Google Chrome wigs out when multiple options have the checked attribute set to true)
self._getOptionsArray().forEach(option => {
option.checked = false;
option.removeAttribute("checked");
});
for (const option of self._getOptionsArray()) {
if (option.value === value) {
option.setAttribute("checked", true);
option.checked = true;
result = option;
break;
}
}
}
return result;
};