【问题标题】:Shiny - checkboxInput within renderDataTable does not work闪亮 - renderDataTable 中的 checkboxInput 不起作用
【发布时间】:2019-11-18 17:58:52
【问题描述】:

我想用 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。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

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

    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)})
        }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2018-05-02
      • 2020-09-18
      • 2021-11-21
      • 1970-01-01
      • 2014-10-09
      • 2019-05-03
      • 2014-07-06
      相关资源
      最近更新 更多