Liky
Liky

Reputation: 1247

Add items to the list of the selectInput by using button (RShiny)

I have the following code:

library(shiny)

vec <- seq(1,10)
ui <- fluidPage(

  titlePanel(""),

  sidebarLayout(
    sidebarPanel(
      fluidRow(
      selectInput("selection", "Select number", vec, multiple = TRUE),
      actionButton("First_fives", "First Fives" ),
      actionButton("Last_fives", "Last Fives"),
      actionButton("ok", "OK"))
    ),

    mainPanel(
      fluidRow(
        h5("Selected numbers:")), 
        textOutput('num')
    )
  )
)

server <- function(input, output, session) {
  observeEvent(input$First_fives,{
    updateSelectInput(session, inputId = "selection", choices = vec[1:5])
  })

  observeEvent(input$Last_fives,{
    updateSelectInput(session, inputId = "selection", choices = vec[6:10])
  })

  data <- reactiveValues()
  observeEvent(input$ok,{
    data$selected <- input$city
  })

  output$num <- renderText({data$selected})

}

shinyApp(ui = ui, server = server)

I almost managed to do what I want but not quite. My selectInput box is empty when running the code and you can select amongst 10 items (from 1 to 10). This is fine. Now I would like, when clicking on the button "First fives", the numbers 1 to 5 to be added to this empty box. In others words I would like to get the same as on the picture below in one click.

enter image description here

Upvotes: 0

Views: 447

Answers (1)

Subhasish1315
Subhasish1315

Reputation: 978

Please add selected on the updateSelectInput. The code will be like this:

 observeEvent(input$First_fives,{
    updateSelectInput(session, inputId = "selection", choices = vec[1:5],selected = vec[1:5])
  })

  observeEvent(input$Last_fives,{
    updateSelectInput(session, inputId = "selection", choices = vec[6:10],selected = vec[6:10])
  }) 

Please not I have only checked this function,not others. Pls check if this meet your requirements.

Upvotes: 1

Related Questions