javascriptrshinydtradio-group

Accessing Radio Button Values in DataTable with multiple page (Shiny)


I can't access radio button values when they're embedded in a data table in shiny with the paging = TRUE option. I base my code on this example : Radio Buttons in DT

This works well for the first page, but not for input on other pages.

Here is the code for the example :

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
  ),
  server = function(input, output, session) {
    m = matrix(
      as.character(1:5), nrow = 12, ncol = 5, byrow = TRUE,
      dimnames = list(month.abb, LETTERS[1:5])
    )
    for (i in seq_len(nrow(m))) {
      m[i, ] = sprintf(
        '<input type="radio" name="%s" value="%s"/>',
        month.abb[i], m[i, ]
      )
    }
    m
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 'Bfrtip', 
                     paging = TRUE, 
                     pageLength = 6,
                     ordering = FALSE),
      callback = JS("table.rows().every(function(i, tab, row) {
          var $this = $(this.node());
          $this.attr('id', this.data()[0]);
          $this.addClass('shiny-input-radiogroup');
        });
        Shiny.unbindAll(table.table().node());
        Shiny.bindAll(table.table().node());")
    )
    output$sel = renderPrint({
      str(sapply(month.abb, function(i) input[[i]]))
    })
  }
)

In this example, I can't access the values of the radio buttons for the months of 'Jul' to 'Dec'. In fact, I have a table with more than 100 rows, and I need to access the input values of the various pages.


Solution

  • Add the preDrawCallback and the drawCallback for Shiny as given by @Stephane Laurent here

     output$foo = DT::renderDataTable(
          m, escape = FALSE, selection = 'none', server = FALSE,
          options = list(dom = 'Bfrtip', 
                         paging = TRUE, 
                         pageLength = 6,
                         preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
                         drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '),
                         ordering = FALSE),
          callback = JS("table.rows().every(function(i, tab, row) {
              var $this = $(this.node());
              $this.attr('id', this.data()[0]);
              $this.addClass('shiny-input-radiogroup');
            });
            Shiny.unbindAll(table.table().node());
            Shiny.bindAll(table.table().node());")
        )