I have a sketch where I create a radio button with 4 options, the last one being selected upon creation inside the setup() function.
When the sketch runs and I resize the window, I want to force selecting the last option. According to the p5.js documentation, I should simply call the selected function passing the value of the last option. This works only the first time selected() is called inside draw(), that is, the first time the window resizes. If I resize again, calling selected doesn’t change the radio button option.
What am I missing?
Thanks!
It looks like this is a bug in p5.js. The code in p5.js for the selected()
function simply finds a matching option and sets the checked
attribute to true. In every browser I’ve tried this is broken. Once all of options have their checked
attribute set it becomes impossible to programmatically set which option is selected. I’ve come up with a simple patch to fix it (see the code fro the fix button):
Note, for whatever reason it is important to click fix
first in this demo for it to work. It would seem that having multiple options with the checked attribute set to true puts them in a bad state, preventing selection in the future.
Paul dude… thanks for the clever workaround. Couldn’t be simpler and it works!
I played with Paul’s sketch a bit more and noticed that while it fixes the radio button behavior, it seems that once I manually select any option, clicking on the next button no longer works reliably. A post in stack overflow mentioned manually checking the “checked” attribute by selecting the proper option using its ID. I modified Paul’s sketch, removing the Fix button and adding his corrected selected() function directly to the radio P5 element, adding different IDs to the options and manually setting the selected option’s checked attribute to true. It works just fine when I manually select an option.
Modified radio button fix
Nice catch.
It turns out that browser actually track the checked state for radio button inputs using a JavaScript property separately/in addition to the checked="true"
attribute . I’ve updated my workaround sketch with the following (which I think is simpler and doesn’t require giving the options id attributes):
// When clearing the state
self._getOptionsArray().forEach(option => {
option.checked = false;
option.removeAttribute("checked");
});
// When setting the selection
option.setAttribute("checked", true);
option.checked = true;
1 Like
Your new sketch inded addresses the issue without IDs. Thanks.