Paul
Paul

Reputation: 11

Use dynamic radioButtons in Shiny

In a Shiny app I create radioButtons dynamically on the server and use renderUI to pass this to the client. Now I have a problem of getting the response of the radioButtons (selected item) back for further processing. Below the stripped down version of my problem.

library(shiny)

ui <- shinyUI(pageWithSidebar(  
    headerPanel("test dynamic radio buttons"),  
    sidebarPanel(    
    ),
    mainPanel(    
        x <- uiOutput('radioTest'),
        actionButton('submit', label = "Submit"),
        br(),
        print(paste("Radiobutton response is:", "reply()")),
        textOutput('text')
    )
))

server <- shinyServer(  
    function(input, output) {
        output$radioTest <- renderUI({
            options <- c("item 1", "item 2", "item 3")
            # The options are dynamically generated on the server
            radioButtons('reply', 'What item do you select ?', options, selected = character(0))
        })
        observe({
            input$submit
            isolate(
                output$text <- renderText({
                    paste("Radiobutton response is:", "reply()" )
                })
            )
        })
    }
)

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 3103

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23129

Do you want something like the following?

library(shiny)

ui <- shinyUI(pageWithSidebar(  
  headerPanel("test dynamic radio buttons"),  
  sidebarPanel(    
  ),
  mainPanel(    
    x <- uiOutput('radioTest'),
    actionButton('submit', label = "Submit"),
    br(),
    #print(paste("Radiobutton response is:", "reply")),
    textOutput('text')
  )
))

server <- shinyServer(  
  function(input, output) {
    output$radioTest <- renderUI({
      options <- c("item 1", "item 2", "item 3")
      # The options are dynamically generated on the server
      radioButtons('reply', 'What item do you select ?', options, selected = character(0))
    })
    observe({
      input$submit

      isolate(
        output$text <- renderText({
          paste("Radiobutton response is:", input$reply )
        })
      )
    })
  }
)

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here

Upvotes: 3

Related Questions