Prevent st.text_input from triggering callback when losing focus

Hi @reuip welcome to the community!

As far as I am concerned in Streamlit, the text_input behavior is the same whether you press Enter or lose focus (@Goyo mentioned it here)

You can workaround this using form and JS โ€˜hackโ€™ for catching ENTER key:

import streamlit as st
import streamlit.components.v1 as components

form = st.form("my_form")
form.text_input("Tell me your secrets", key="text")
form.form_submit_button("Submit")

st.write("if enter pressed")
st.write(st.session_state["text"])

components.html(
    """
<script>
const doc = window.parent.document;
buttons = Array.from(doc.querySelectorAll('button[kind=secondaryFormSubmit]'));
const submit = buttons.find(el => el.innerText === 'Submit');

doc.addEventListener('keydown', function(e) {
    switch (e.keyCode) {
        case 13: // (37 = enter)
            submit.click();
    }
});
</script>
""",
    height=0,
    width=0,
)

Iโ€™m using inputs catching quite intensive in some of my projects :slight_smile:

2 Likes