问题
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)
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.
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/52822999/disable-an-item-in-selectinput-dropdown