thothal
thothal

Reputation: 20329

Update sliderInput in Shiny reactively

I am trying to change the values from a sliderInput dynamically. The difficulty now is that I want to change from a sliderInput with one value, to a sliderInput with a range, which seems not to work.

The first actionbutton in the code below works, while the second does not what it is intended to do.

Is the only possibility to switch to an uiOutput element?

Code

library(shiny)
app <- shinyApp(
   ui = bootstrapPage(
      sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5),
      actionButton("acb1", "Change Value"),
      actionButton("acb2", "Change Value to Range")
   ),
   server = function(input, output, session) {
      observeEvent(input$acb1, {
         updateSliderInput(session, "sld1", value = 2)
      })
      observeEvent(input$acb2, {
         updateSliderInput(session, "sld1", value = c(2,7))
      })
   })
runApp(app)

Upvotes: 6

Views: 4086

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

You can maybe add the slider dynamically using renderUI

#rm(list = ls())
library(shiny)
app <- shinyApp(
  ui = bootstrapPage(
    uiOutput("myList"),
    actionButton("acb1", "Change Value"),
    actionButton("acb2", "Change Value to Range")
  ),
  server = function(input, output, session) {

    slidertype <- reactiveValues()
    slidertype$type <- "default"

    observeEvent(input$acb1,{slidertype$type <- "normal"})
    observeEvent(input$acb2, {slidertype$type <- "range"})

    output$myList <- renderUI({

      if(slidertype$type == "normal"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 2)
      }
      else if(slidertype$type == "range"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = c(2,7))
      }
      else{
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5)
      }
    })    
})
runApp(app)

Upvotes: 7

Related Questions