Hello,
I am trying to create multiple boxes that the user can display or not through a checkbox, in which a selectbox allow the user to choose an option. My problem is that I want each selectbox to stay on the option the user chose, even if the box is closed and then reopened… I tried doing it with st.session_state by introducing a variable “last_selected_option” which I could get the index from in the st.selectbox, but I have trouble initializing it. When I give it the value None, the code rightfully does not find function index for attribute None. Do you know how I could initialize it correctly ? Here is the bit a code below :
1 Like
Hi @BenjaminLamballais
Instead of initializing the value as None
for the session state variable of the selectbox index value, you can initialize it as 0
.
Consider the following example code snippet:
import streamlit as st
if 'selectbox_option' not in st.session_state:
st.session_state.selectbox_option = 0
option_list = ['Email', 'Home phone', 'Mobile phone']
option = st.selectbox(
'How would you like to be contacted?',
option_list,
index=st.session_state.selectbox_option)
# Index value of selected option
st.session_state.selectbox_option = option_list.index(option)
st.write('Index:', st.session_state.selectbox_option)
# Selected option
st.write('You selected:', option_list[st.session_state.selectbox_option])
Hope this helps!
1 Like
Hi,
When I try the following code with initialized value at 0, I get the following errors :
I made sure that the line “st.session_state[“submitted_config”]=st.form_submit_button(“Submit data”)”
was included in the st.form, so I don’t really understand where the problem comes from.
1 Like
Hi,
Could you try adding 1 more indentation to the st.form_submit_button(…)
line and see if that helps since there’s an if
conditional.
1 Like
I get the following error now :
1 Like