pythonpy-shiny

How to use the input of a field only if it is visible?


How do I manage that an input field value is empty, if it is not shown. In the example the text caption field is empty and not shown. If I show it by ticking "Show text caption field" and enter any text, the text appears in the output field. If I then untick "Show text caption field" the output field should also be empty again without having to manually. Not in general of course, but for some use cases this is quite important.

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

app_ui = ui.page_fluid(
    ui.input_checkbox("show", "Show text caption field", False),
    ui.panel_conditional(
        "input.show", 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()


app = App(app_ui, server)

Solution

  • Here you can extend the render.text such that the displayed value of the ui.output_text_verbatim is input.caption() if input.show() else "":

    from shiny import App, Inputs, Outputs, Session, render, ui
    
    app_ui = ui.page_fluid(
        ui.input_checkbox("show", "Show text caption field", False),
        ui.panel_conditional(
            "input.show", 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() if input.show() else "" 
    
    app = App(app_ui, server)
    

    enter image description here