Hi, I’m creating a page with multiple selectboxes
The options available in the second selectbox are influenced by the option that the user picks in the first selectbox:
st.selectbox("SelectBox 1", ["choice A", "choice B"], index=None, key="selectbox1")
selectbox1_pick = st.session_state["selectbox1"]
if selectbox1_pick is None:
selectbox2_options = []
elif selectbox1_pick == "choice A":
selectbox2_options = ["only one choice"]
elif selectbox1_pick == "choice B":
selectbox2_options = ["Alpha", "Beta", "Gamma"]
else:
raise ValueError
st.selectbox("SelectBox 2", selectbox2_choices,
index=0 if len(selectbox2_options) == 1 else None, key="selectbox2")
The behavior I am trying to achieve is this:
If the user picks choice A
from selectbox1
, then selectbox2
will have only one available option: only one choice
. Since this is the only available option, it should be auto-selected by the code in order to prevent the user from having to click on the selectbox and choose the only option that is available.
I am trying to get this behavior with
index=0 if len(selectbox2_options) == 1 else None
when defining selectbox2. However, the second selectbox always defaults to choose an option
instead of defaulting to only one choice
in case selectbox1
is set to choice A
.
Before selecting anything in SelectBox1
:
After picking choice A
this happens:
(notice that SelectBox2
is still displaying Choose an option
)
What I would like to happen instead is that SelectBox2
automatically selects the only available option:
How can I accomplish the auto-select behavior in the case where the number of options is exactly 1?