Get text input when user pressed "RETURN" key

Hi Streamlit, pardon me if this is a duplicate question while I did have tried to search but failed.

I have a text_input widget and trying to capture the event when user presses “RETURN” key. But I cannot tell it apart from other events of user interacting with other widgets. The code goes like following:

size = st.selecbox("Choose size:", ["Large", "Medium", "Small"])
text = st.text_input("Search by tag")

if user_pressed_RETURN_in_text_input:    # <---  How can I do this?
    data = do_search_by_tag(text)
else:     # user chose an option in the select box
    data = do_search_by_size(size)

Any advice is appreciated.

Hi @cuteufo, welcome to the Streamlit community :slight_smile:

At this time it is not possible to capture specific keypress events other than ENTER on the text_input.

I do think it’s a good usecase for the upcoming Custom Components, which should be out soon, and will enable you to write your own JS/HTML rendered in Streamlit apps. When that comes out you should be able to overwrite this behavior and catch your own keypress events !


Hi @andfanilo, thanks for your reply. I assume “Enter” is identical to “Return” in this context.

My scenario is that the two widgets, select box and text input, are not treated as AND, but only one of them will influent the result, so what I want is to check which widget I get input from, depending on which widget the user has interacted with. If user types something in the text input and pressed “Enter” (“Return”) key, I will use text input and neglect the options in select box. Otherwise, if the user selects one option in the select box, I will only take that option into account. The challenge for me is I didn’t find a way to check if the text input has received a “Enter” events. Please advice me if I overlooked something from the documents.

For now, what I did to achieve this is to place a button next to the text input and let user click the button, so I can get a condition like if search_by_tag_button is True:. This works, but the text input often shows a hint like “Press Enter” in gray to distract user from clicking the button.