3

How do I disable an item in a selectInput() dropdown menu?

For example;

library(shiny)
ui <- fluidPage(selectInput("id1","Select",choices=c("A","B","C")))
server <- function(input, output) {}
shinyApp(ui, server)

enter image description here

Say, for whatever reason, option C cannot be selected due to some logic. I would like the user to be able to see all the options, but have option C disabled/unselectable.

mindlessgreen
  • 11,059
  • 16
  • 68
  • 113

2 Answers2

4

You can do this using pickerInput from package shinyWidgets :

library(shiny)
library(shinyWidgets)
ui <- fluidPage(
  pickerInput(
    inputId = "id1",
    label = "Select :",
    choices = c("A", "B", "C"),
    multiple = FALSE,
    choicesOpt = list(
      disabled = c("A", "B", "C") %in% c("C")
    )
  ),
  verbatimTextOutput(outputId = "result")
)
server <- function(input, output) {
  output$result <- renderPrint(input$id1)
}
shinyApp(ui, server)

That's also possible to do that from the server, see example in ?updatePickerInput

Victorp
  • 13,636
  • 2
  • 51
  • 55
  • What if I want to disable the current selection after it has been selected? So that the individual cannot select it again? When I try that I get an error... which I think is due to the fact that a lot of other elements on the app are dependent on the current selection. Does that make sense? – AyeTown May 14 '20 at 17:55
-1

I believe it can't be done with standard shiny. You can try to apply some css/js magic if you know it (e.g., turn not selectable items to red color and give a message to user if they chose it anyways, or maybe you can directly disable clicking on them with js/css, not sure, see sendCustomMessage()).

Another option would be to use updateSelectInput() to discard not needed items from the dropdown when you need it.

update:

I did a quick search on it -- as I can see it is doable with html option disabled, e.g.

<select>
  <option value="volvo" disabled>Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi">Audi</option>
</select>

All you need to do is to generate shiny's selectInput on the server (probably with renderUI()) and add that disabled option to the elements you need to disable

vladli
  • 1,454
  • 2
  • 16
  • 40