实现PickerInput的全选功能,并在点击"all"时显示所有选项
P粉665679053
P粉665679053 2023-09-09 14:36:29
0
1
674

在下面的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: blockdisplay: 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)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板