Ty Voss
Ty Voss

Reputation: 283

r shiny user input based on choice

I know how to add a text input or radio button or date input on the UI, what I am trying to do is, ask the user whether he wants to enter a text or a date range? Depending on what the user chooses either show a text input or date input. Not sure how to do this.

       Pseudo Code

       1) Please choose if you want to enter text or date range.
            Radio Button 1 - Text Input
            Radio Button 2 - Date Range

       2a) If the user chooses Radio Button 1, then Text Input should be displayed on the main panel, option to enter two dates (From & to) should not be displayed

       2b) If the user chooses Ratio Button 2, then the option to enter two dates (From & to) should be displayed on the Main panel and text input should not be displayed.

Not sure how to do this. Need some pointers.

Upvotes: 3

Views: 1479

Answers (1)

cdeterman
cdeterman

Reputation: 19970

I am feeling generous here, generally you should provide your attempted code but here is a working example of how to have conditional inputs.

library(shiny)

runApp(
    list(
        ui = pageWithSidebar(
            headerPanel("Option Input via Radio Buttons"),
            sidebarPanel(
                radioButtons("radio", label = h3("Radio buttons"),
                             choices = list("Date" = "date", "Text" = "text"), 
                             selected = 1),
                uiOutput("textORdate")
                ),
            mainPanel()
            ),
        server = function(input, output){
            output$textORdate <- renderUI({
                validate(
                    need(!is.null(input$radio), "please select a input type")
                    )
                if(input$radio == "text"){
                    textInput("mytext", "Text Input", "please enter text")
                }else{
                    dateRangeInput("daterange", "Date range:",
                                   start = "2012-01-01",
                                   end   = "2015-03-06")
                }
            })
        }))

There are multiple concepts I am demonstrating here. Firstly, you can create your dynamic inputs by creating your input in your server.R section. This is then displayed by uiOutput. Secondly, I always like to introduce people to validate. This is an important function to help troubleshoot or provide the user helpful error messages.

Upvotes: 1

Related Questions