I was wondering how we could go about introducing an indeterminate property to the new anvil-m3-switch. I see back in the day there was a similar discussion about Indeterminate checkboxes
Has anyone done something similar with either the anvil-extras switch or the new m3 switch?
M3 doesn’t have specs for an indeterminate switch. To be honest, I’m not sure what that would look like or what the purpose of it would be. My gut instinct is that it would be bad UX. The purpose of a switch is to turn something on or off. @Neeeco what is your use case?
It comes down to a client request. They don’t like the look of a checkbox (which has indeterminate state), they prefer a switch.
However, in their use case we don’t want the value to be preset to either True or False. The user must explicitly select True/False in order to go to the next step in the flow.
I have created a custom component here and it works great… if I only have one such switch… My JS knowledge is limited, but I know the problem is because I’m declaring something twice… Would love it if someone can help me get this to work so that I can add two or more of these switches to a form.
I can’t really argue with a client request, but I still maintain that this use case violates the purpose of a switch! So I can’t say we have any plans to implement one in M3.
However, in terms of your implementation of the switch. The simplest answer is that in HTML, id should be unique. You are setting the id of your HTML element to be “switch” and using document.getElementById() in JS. This blows up when you have multiple switches on the screen because it is looking for a single element with that id. You could set a unique id for each switch, but my suggestion would be to implement your component differently.
Your component’s HTML has <html>, <head> and <meta> and <title> tags, which you don’t need here. I would also put the css in your theme.css file instead of using a <style> script. And instead of using JS to implement the logic for your component, I would use Python. This will eliminate the need for getElementById. I’m not sure if you’ve seen the docs on custom components from HTML, but it might be helpful: Anvil Docs | Components from HTML. You can also look at the code for the Material 3 theme for examples: GitHub - anvil-works/material-3-theme: Anvil's Material 3 Theme.
Just to be clear, I do understand the use case. From a UI/UX perspective, I just don’t think a switch is appropriate since switches are meant to only have two states. However, as @Neeeco has said, the client is always right! And in my case, you are the client!
Read the docs for the first time and SO MUCH easier to do all the logic python side! Thanks @brooke . I have updated the clone link to include the pythonised way of doing it if anyone else want to use it or take it further. Indeterminate Switch - #3 by Neeeco
For my use case, the current state will do.
@stucork thanks for the anvil-extras pointer, might try that one as well.