Search code examples
pythonpy-shiny

How to change the value of an ui.input element based on another input?


Is it possible to change the default value of an py-shiny ui.input element based on another input? In the example if I tick "Use uppercase letters" the value should switch from "example text" to "EXAMPLE TEXT".

from shiny import App, Inputs, Outputs, Session, render, ui

app_ui = ui.page_fluid(
    ui.input_checkbox("Uppercase", "Use uppercase letters", False),
    ui.input_text("caption", "Caption:", value="example text"),
    ui.output_text_verbatim("value"),
)


def server(input: Inputs, output: Outputs, session: Session):
    @render.text
    def value():
        return input.caption()


app = App(app_ui, server)

Solution

  • You can define an reactive.effect containing an ui.update_text which updates the value depending on input.Uppercase():

    from shiny import App, Inputs, Outputs, Session, render, ui, reactive
    
    app_ui = ui.page_fluid(
        ui.input_checkbox("Uppercase", "Use uppercase letters", False),
        ui.input_text("caption", "Caption:"),
        ui.output_text_verbatim("value"),
    )
    
    def server(input: Inputs, output: Outputs, session: Session):
        @render.text
        def value():
            return input.caption()
    
        @reactive.effect
        def _():
            ui.update_text(
                "caption",
                value="EXAMPLE TEXT" if input.Uppercase() else "example text"
            )
    
    app = App(app_ui, server)
    

    enter image description here