Deactivate shiny selectInput() choices from being selected

In the shiny app below I have a selectInput() in which I want only the choices to be displayed but it will not be possible to select another one of the choices than the selected one. In a few words I want it deactivated and only for display.

## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
library(shinyjs)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
  ),
  dashboardBody(
    useShinyjs(),
    uiOutput("sel")
      )
      )


server <- function(input, output,session) {
  output$sel<-renderUI({
    selectInput("ir","Select",choices = unique(iris$Species),selected=unique(iris$Species)[1],multiple = F)
    
  })
  observeEvent(input$ir, { updateSelectInput(session, "ir", selected=as.character("sel")[1]); })
}

shinyApp(ui, server)  

>Solution :

Perhaps this?

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      shinyjs::useShinyjs(),
      uiOutput("sel")
    )
  ),
  server = function(input, output, session) { # add session so we can update
    val <- as.character(unique(iris$Species)[1])
    output$sel<-renderUI({
      out <- selectInput("ir","Select",choices = unique(iris$Species),selected=val,multiple = F)
      observeEvent(input$ir, { updateSelectInput(session, "ir", selected=val); })
      out
    })
  }
)

It does allow the user to temporarily select something else, but it immediately changes back to the desired value.

If you need to depend on input$ir for some reason, the reactive components will likely see the change away from and back to the desired value. To protect against this, I suggest a reactiveVal that tracks what value you want other elements to react to, and use that. For instance,

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      shinyjs::useShinyjs(),
      uiOutput("sel")
    )
  ),
  server = function(input, output, session) {
    val <- reactiveVal(unique(iris$Species)[1])
    output$sel<-renderUI({
      out <- selectInput("ir","Select",choices = unique(iris$Species),selected=val(),multiple = F)
      observeEvent(input$ir, { updateSelectInput(session, "ir", selected=val()); })
      out
    })
    somethingelse <- reactive({
      # do something with val()
    })
  }
)

Leave a Reply