Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Enable/Disable Form Fields in Streamlit

I have a form in Streamlit that looks something like this,

with st.form("my_form"):
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"])

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')

Now, I want my second dropdown field, i.e. drop_down_2 to appear only if a certain value in drop_down_1 is selected, say Option 1.

How can I achieve this?

I tried something like this, but it did not work.

with st.form("my_form"):
   is_drop_down_2_disabled = True
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   if drop_down_1 == 'Option 1':
       is_drop_down_2_disabled = False

   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=is_drop_down_2_disabled)

   submitted = st.form_submit_button("Submit")
   if submitted:
       submission_state = st.text('Form Submitted!')

I assume that this is because the variables within the form are not assigned any values until the Submit button is clicked.

like image 869
Minura Punchihewa Avatar asked Feb 20 '26 21:02

Minura Punchihewa


1 Answers

The functionality of st.form is to not re-run the code until submitted. If you want that to happen, just don't put the button inside the form. You can split the form into two, it's not affecting the layout. However, if you want to store a value from the form and use it to change something, you need to use session state to save the button value:

import streamlit.session_state as ss

with st.form("my_form"):
   ss.is_drop_down_2_disabled = True
   text_input_1 = st.text_input("Input 1")

   drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
   if drop_down_1 == 'Option 1':
       ss.is_drop_down_2_disabled = False

   drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=ss.is_drop_down_2_disabled)

   ss.submitted = st.form_submit_button("Submit")
   if ss.submitted:
       submission_state = st.text('Form Submitted!')
like image 190
Johannes Schöck Avatar answered Feb 24 '26 01:02

Johannes Schöck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!