我想出了一些在选项列表中添加不可见空间的好主意。我还通过在开头添加“”选项来欺骗选择,这解决了删除最后一个元素时缺乏反应性的问题。
这几乎可以完成这项工作 - 添加项目时非常出色。
还有两个无法解决的问题:
- 下拉列表每次都会关闭(无法修复,因为需要更新输入)
- 删除项目时,下拉列表中的选项过多
代码:
library(shiny)
library(dplyr)
server <- function(input, output, session) {
# set the default choices and set previous selection to initial selectInput vector
globalList <- reactiveValues(ManyChoices = LETTERS[1:3], SelectedPrev = c())
output$multipleSelect <- renderUI({
selectizeInput("selectMany",
label = "I want to select each multiple times",
choices = c(" ", globalList$ManyChoices),
selected = " ",
multiple = TRUE,
options = list(closeAfterSelect = TRUE, openOnFocus = TRUE))
})
observeEvent(input$selectMany, {
# if sth was added
if(length(input$selectMany) > length(globalList$SelectedPrev)) {
#find out what was modified
vDiff <- setdiff(input$selectMany, globalList$SelectedPrev) %>% setdiff(., " ")
# used when removing " " and selecting sth to double the selection
if(length(vDiff) == 0) vDiff <- input$selectMany[length(input$selectMany)]
req(input$selectMany != " ") # if only " " is selected then there is no need to update
# get the position of selected element
vIndex <- which(globalList$ManyChoices == vDiff)
vLength <- length(globalList$ManyChoices)
# create new choices in the correct order
globalList$ManyChoices <- c(globalList$ManyChoices[1:vIndex],
paste0(vDiff, " "),
if(vIndex < vLength) {globalList$ManyChoices[(vIndex + 1):vLength]})
} else {
# remove the version with additional space when value was removed
vDiff <- setdiff(globalList$SelectedPrev, input$selectMany)
globalList$ManyChoices <- setdiff(globalList$ManyChoices, paste0(vDiff, " "))
}
# update previous selection
globalList$SelectedPrev <- input$selectMany
# update input with same selection but modified choices
updateSelectizeInput(session = session,
inputId = "selectMany",
selected = c(" ", input$selectMany),
choices = c(" ", globalList$ManyChoices))
})
}
ui <- function() {
fluidPage(
uiOutput("multipleSelect")
)
}
shinyApp(ui, server)