實現PickerInput的全選功能,並在點擊"all"時顯示所有選項
P粉665679053
P粉665679053 2023-09-09 14:36:29
0
1
693

在下面的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粉665679053
P粉665679053

全部回覆(1)
P粉739942405

這是一個基於這個很好的答案的範例。我們在這裡使用了一個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)
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板