首页 > 解决方案 > 闪亮 - renderDataTable 中的 checkboxInput 不起作用

问题描述

我想用 renderDataTable() 函数在 Shiny 中显示一个表格。对于每一行,我想创建 2 个复选框。我正在使用 checkboxInput() 函数来创建这些复选框。复选框已创建,但当我尝试使用 input$checkbox_id 读取它们时,我得到 NULL。

使用 renderTable() 可以实现相同的技巧,但我的客户想要 DT 表的额外功能(排序、过滤)。

如果我检查生成的 HTML,我会看到 renderTable() 将额外的 class="shiny-bound-input" 插入到标签中。renderDataTable() 没有。

library(shiny)
shinyApp(
    ui = fluidPage(
       fluidRow(
         column(12,dataTableOutput('dataTableOutput')),
         column(12,tableOutput('tableOutput')),
         actionButton('printCheckStatus','printCheckStatus')
       )
     ),
     server = function(input, output) {
       df1 <- data.frame(CheckBoxColumn=as.character(checkboxInput("id_1",NULL)))
       df2 <- data.frame(CheckBoxColumn=as.character(checkboxInput("id_2",NULL)))
       output$dataTableOutput <- renderDataTable(df1,escape = FALSE)
       output$tableOutput <- renderTable(df2, sanitize.text.function = function(x) x)

       observeEvent(input$printCheckStatus, {print(input$id_1);print(input$id_2)})
     }
)

该代码生成一个按钮和两个表,每个表都包含一个复选框。当我单击按钮时,我在控制台中得到 NULL 和 FALSE。FALSE 是正确的,因为第二个复选框未选中。我得到 NULL 因为在 Shiny 服务器会话中不存在 input$id_1 。我希望控制台日志中有 FALSE 和 FALSE。

标签: rshiny

解决方案


您可以使用 DT 包(基于):

library(shiny)
library(DT)
shinyApp(
    ui = fluidPage(
        fluidRow(
            column(12,dataTableOutput('dataTableOutput')),
            column(12,tableOutput('tableOutput')),
            actionButton('printCheckStatus','printCheckStatus')
        )
    ),
    server = function(input, output) {
        df1 <- data.frame(CheckBoxColumn=as.character(checkboxInput("id_1",NULL)))
        df2 <- data.frame(CheckBoxColumn=as.character(checkboxInput("id_2",NULL)))
        output$dataTableOutput <- renderDataTable(df1,escape = FALSE, server = FALSE, 
        callback = JS("table.cells().every(function(i, tab, cell) {
          var $this = $(this.node());
          $this.attr('id', this.data()[0]);
          $this.addClass('shiny-input-checkbox');
        });
        Shiny.unbindAll(table.table().node());
        Shiny.bindAll(table.table().node());"))
        output$tableOutput <- renderTable(df2, sanitize.text.function = function(x) x)

        observeEvent(input$printCheckStatus, {print(input$id_1);print(input$id_2)})
    }
)

推荐阅读