如何制作 shinyWidget 材质切换更新复选框GroupButtons

How to make shinyWidget materialSwitch update checkboxGroupButtons

提问人:Tom Wagstaff 提问时间:11/16/2023 最后编辑:Tom Wagstaff 更新时间:11/16/2023 访问量:14

问:

我想在切换时使用 materialSwitch 在相邻的一组 checkboxGroupButtons 中全选/取消全选。但在下面的代码中,开关对复选框没有影响:shinyWidgets

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  checkboxGroupButtons(
    inputId = "somevalue",
    choices = c("A", "B", "C"),
    label = "My label"
  ),
  
  verbatimTextOutput(outputId = "res"),
  
  materialSwitch(
    inputId = "clear",
    label = "Select all?",
    value = TRUE, 
    status = "info"
  )

)

server <- function(input, output, session) {
  
  output$res <- renderPrint({
    input$somevalue
  })
  
  observeEvent(input$clear, {

    if (input$clear) {
      updateCheckboxGroupInput(session, "somevalue", selected = c("A", "B", "C"))
    } else {
      updateCheckboxGroupInput(session = session, inputId = "somevalue", selected = character(0))
    }

  })  

}

shinyApp(ui = ui, server = server)

我认为问题出在 if 语句中,就好像我跳过了可以更新复选框组,每次点击时都可以选择全部或取消选择全部。我也尝试过使用而不是这里建议,但没有效果。observeobserveEvent

谁能把我说对?

r 闪亮 闪亮的小部件

评论


答:

0赞 YBS 11/16/2023 #1

with you should use , and with you can use .他们俩都工作。试试这个checkboxGroupButtonsupdateCheckboxGroupButtonscheckboxGroupInputupdateCheckboxGroupInput

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  checkboxGroupButtons(
  # checkboxGroupInput(
    inputId = "somevalue",
    choices = c("A", "B", "C"), selected = c("A", "B"),
    label = "My label"
  ),
  
  verbatimTextOutput(outputId = "res"),
  
  materialSwitch(
    inputId = "clear",
    label = "Select all?",
    value = TRUE, 
    status = "info"
  )
  
)

server <- function(input, output, session) {
  
  output$res <- renderPrint({
    input$somevalue
  })
  
  selection <- eventReactive(input$clear, {
    selected = character(0)
    if (input$clear) {
      selected = c("A", "B", "C")
    } 
    selected
  })
  
  observeEvent(selection(), {
    updateCheckboxGroupButtons(session, 
    # updateCheckboxGroupInput(session, 
                             inputId = "somevalue",
                             choices = c("A", "B", "C"),
                             selected = selection())
  },ignoreNULL = FALSE, ignoreInit = TRUE)  
  
}

shinyApp(ui = ui, server = server)