I have a selectinput with multiple = TRUE, I need to disable the selectinput once user select the multiple choices. But the selectinput is disabling once I select the first choice and it is not allowing me to select second choice. I have used following code.
library(shiny)
library(shinyjs)
ui <- fluidPage(
br(),
useShinyjs(),
fluidRow(
column(
width = 6,
selectInput(inputId = "check1", label = "Choose", choices = c("choice A","choice B","choice C"),multiple = T),
verbatimTextOutput(outputId = "res1")
)
)
)
server <- function(input, output, session) {
flag_lifecycle <- reactiveValues(val = "Yes")
output$res1 <- renderPrint({
input$check1
})
observeEvent(input$check1, {
shinyjs::disable("check1")
})
}
shinyApp(ui = ui, server = server)
The output I got
Here, selectinput should be disabled only when multiple choice has been selected.
Any help here is appreciated. Thanks in advance!
CodePudding user response:
In the current setup you don't actually know when user has finished the selection.
Consider various scenarios -
- If you disable after 1st selection then user cannot select 2 or 3 values.
- If you disable after 2nd selection then user cannot select 3 values.
- If you disable after 3rd then what if user only want to select 1 value ?
You'll never know when to disable based on length of values. I think a better option would be to provide an actionButton
for user to submit after they are done with their selection.
library(shiny)
library(shinyjs)
ui <- fluidPage(
br(),
useShinyjs(),
fluidRow(
column(
width = 6,
selectInput(inputId = "check1", label = "Choose",
choices = c("choice A","choice B","choice C"), multiple = T),
verbatimTextOutput(outputId = "res1"),
actionButton('submit', 'Done')
)
)
)
server <- function(input, output, session) {
flag_lifecycle <- reactiveValues(val = "Yes")
output$res1 <- renderPrint({
input$check1
})
observeEvent(input$submit, {
shinyjs::disable("check1")
})
}
shinyApp(ui = ui, server = server)
CodePudding user response:
Use selectizeInput()
.
The function below adds 2 functionalities to your selectizeInput()
:
- Ability to remove an already made choice.
- Limit max number of items that can be selected.
# ----selectizeInput options---
selectizeOptions <- function (n = NULL) { # n is the max number of items
if (is.null(n)) {
list(
plugins = list("remove_button")
)
}else {
list(
plugins = list("remove_button"),
maxItems = n
)
}
}
Here is an example:
library(shiny)
ui <- fluidPage(
# ----selections here----
selectizeInput(
inputId = "thechoices",
label = "Choose",
choices = LETTERS,
selected = "A",
multiple = TRUE,
options = selectizeOptions(n = 4)
)
)
server <- function(input, output, session) {
}
shinyApp(ui, server)