在下面的shiny
應用程式中,當所有pickerInput()
的選項都被選擇時,我希望在pickerInput()
內部顯示單詞"all"
作為選項,當您點擊它時,將顯示所有三個選項。如果我們可以用selectInput()
實現,那就沒有問題,但列印的輸出不應受影響。我該怎麼做呢?
library(shiny) library(shinyWidgets) ui <- fluidPage( uiOutput("pick"), verbatimTextOutput("PR") ) server <- function(input, output, session) { output$pick<-renderUI({ pickerInput( inputId = "p9", label = "健康保险", choices = unique(as.character(iris$Species)), width = "150px", selected = unique(as.character(iris$Species)), multiple = TRUE, options = list( `actions-box` = TRUE, `deselect-all-text` = "无", `select-all-text` = "全部", `none-selected-text` = "零" ) ) }) output$PR<-renderPrint({ input$p9 }) } shinyApp(ui, server)
P粉7399424052023-09-10 11:51:56
這是一個基於這個很好的答案的範例。我們在這裡使用了一個clickHandler
,它根據容器All
的點擊情況,改變dropdown-item
的樣式,使其在display: block
和display: none
之間切換。請注意,在應用程式初始化時,如果所有選擇都被選中,項目只會隱藏在All
後面。
library(shiny) library(shinyWidgets) js <- HTML( " $(function() { let observer = new MutationObserver(callback); function clickHandler(evt) { if ($('.dropdown-item').css('display') == 'block') { $('.dropdown-item').on('click', clickHandler).css('display', 'none'); } else { $('.dropdown-item').on('click', clickHandler).css('display', 'block'); } } function callback(mutations) { for (let mutation of mutations) { if (mutation.type === 'childList') { $('.dropdown-header').on('click', clickHandler).css('cursor', 'pointer'); if ($('#p9 option').length == $('#p9 :selected').length) { $('.dropdown-item').on('click', clickHandler).css('display', 'none'); } } } } let options = { childList: true, }; observer.observe($('.inner')[0], options); }) " ) choices <- list("All" = unique(as.character(iris$Species))) ui <- fluidPage( tags$head(tags$script(js)), pickerInput( inputId = "p9", label = "Health Insurance", choices = choices, width = "150px", selected = unlist(unname(choices)), multiple = TRUE, options = list( `actions-box` = TRUE, `deselect-all-text` = "None", `select-all-text` = "All", `none-selected-text` = "zero" ) ), verbatimTextOutput("PR") ) server <- function(input, output, session) { output$PR <- renderPrint({ input$p9 }) } shinyApp(ui, server)