带有垂直单选按钮的闪亮DT数据表

时间:2018-12-03 23:40:51

标签: javascript r shiny dt

我需要一个闪亮的DT数据表,该数据表中嵌入了单选按钮。 This app显示了针对水平按钮的解决方案,因此我开始针对垂直情况进行调整。矩阵很容易修改(请参见下面的代码),但是由于缺乏JavaScript知识,我陷入了回调部分。有任何想法吗?

更新:除非必须使用单选按钮,否则使用DT中的行选择功能会更容易,只需设置selection =“ single”,这样就只能选择一行。 / p>

library(shiny)
library(DT)
m = matrix(
  as.character(1:12), nrow = 12, ncol = 5, byrow = FALSE,
  dimnames = list(month.abb, LETTERS[1:5])
)
for (i in seq_len(ncol(m))) {
  #for (i in 1) {
  m[,i ] = sprintf(
    '<input type="radio" name="%s" value="%s"/>',
    LETTERS[i], m[,i]
  )
}

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
  ),
  server = function(input, output, session) {
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, 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({
      input[["A"]]
    })
    }
)

1 个答案:

答案 0 :(得分:0)

library(shiny)
library(DT)

m = matrix(
  as.character(1:12), nrow = 12, ncol = 5, byrow = FALSE,
  dimnames = list(month.abb, LETTERS[1:5])
)
for (i in seq_len(ncol(m))) {
  m[, i] = sprintf(
    '<input type="radio" name="%s" value="%s"/>',
    LETTERS[i], m[,i]
  )
}

callback <- c(
  "var LETTERS = ['A','B','C','D','E'];",
  "for(var i=0; i < LETTERS.length; ++i){",
  "  var L = LETTERS[i];",
  "  $('input[name=' + L + ']').on('click', function(){",
  "    var name = $(this).attr('name');",
  "    var value = $('input[name=' + name + ']:checked').val();",
  "    Shiny.setInputValue(name, value);",
  "  });",
  "}"
)

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
  ),
  server = function(input, output, session) {
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE),
      callback = JS(callback)
    )
    output$sel = renderPrint({
      input[["A"]]
    })
  }
)