How to call an event whenever the value of radio changes

Summary

How to call an event whenever the value of radio changes

Steps to reproduce

Code snippet:

with request:
    with st.form("title_or_description_form"):

        title_or_description = st.radio(
            "Title or Description",
            ('Title', 'Description'),
            horizontal=True,
            index=1,
            on_change=lambda x: st.write(x)) # ERROR
            )
        st.markdown("---")

        option_recommendation_text_length = st.number_input('Recommendation text length', value=75)

        submitted = st.form_submit_button("Submit")
        if submitted:
            if title_or_description == 'Title':
              // something
              // use title_or_description, option_recommendation_text_length

Expected behavior:

Whenever the value of radio changes, I want the value of option_recommendation_text_length to change and be displayed on the screen.

However, I can’t seem to use radio’s on_change in the process and would like some help.

Actual behavior:

I want the value of option_recommendation_text_length to change from 20 to 30 whenever the selection of radio(field title_or_description) changes.

To accomplish this, I use the on_change of radio and get the following error.

streamlit.errors.StreamlitAPIException: With forms, callbacks can only be defined on the `st.form_submit_button`. Defining callbacks on other widgets inside a form is not allowed.

The error makes sense, but I have no idea how to fix it.

Ifixed it to look like the code below.

with request:
    title_or_description = st.radio(
        "Title or Description",
        ('Title', 'Description'),
        horizontal=True,
        index=1)

    with st.form("title_or_description_form"):

        if title_or_description == 'Title':
            option_recommendation_text_length = st.number_input('Recommendation text length', value=20)
        else:
            option_recommendation_text_length = st.number_input('Recommendation text length', value=75)
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.