【问题标题】:Move to the next row of the selected one in a DT::datatable with the use of an actionButton()使用 actionButton() 移动到 DT::datatable 中所选行的下一行
【发布时间】:2021-04-20 02:43:02
【问题描述】:

我在下面有一个闪亮的应用程序,我在其中单击数据表行并在其旁边显示其索引。是否可以按Next 按钮并显示下一行的索引?表格的下一行也会相应地突出显示。

library(shiny)
library(DT)


shinyApp(
  ui = fluidPage(
    title = 'Select Table Rows',
    
    h1('A Server-side Table'),
    
    fluidRow(
      column(9, DT::dataTableOutput('x3')),
      column(3, verbatimTextOutput('x4')),
      actionButton("next","Next row")
    )
    
  ),
  server = function(input, output, session) {

    # server-side processing
    mtcars2 = mtcars[, 1:8]
    output$x3 = DT::renderDataTable({datatable(selection = list(target = "row", mode = "single"),mtcars2 )})
    
    # print the selected indices
    output$x4 = renderPrint({
      s = input$x3_rows_selected
      if (length(s)) {
        cat('These rows were selected:\n\n')
        cat(s, sep = ', ')
      }
    })
})

【问题讨论】:

标签: r shiny dt


【解决方案1】:
library(shiny)
library(DT)

dat <- iris[1:6,]

callback <- JS(
  "$('#btn-next').prop('disabled', true);",
  "var selected_row = null;",
  "table.on('select', function( e, dt, type, indexes ) {",
  "  $('#btn-next').prop('disabled', false);",
  "  selected_row = indexes[0];",
  "});",
  "table.on('deselect', function( e, dt, type, indexes ) {",
  "  $('#btn-next').prop('disabled', true);",
  "});",
  "var nrows = table.rows().count();",
  "$('#btn-next').on('click', function() {",
  "  var next_row = selected_row + 1 < nrows ? selected_row + 1 : 0;",
  "  table.row(next_row).select();",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("dtable"),
  br(),
  splitLayout(
    textOutput("selectedRow"),
    actionButton("btn-next", "select next row"),
    cellWidths = "150px"
  )
)

server <- function(input, output, session) {
  
  output[["dtable"]] <- renderDT({
    datatable(
      dat, 
      extensions = "Select",
      selection = "none",
      callback = callback,
      options = list(
        columnDefs = list(
          list(className = "dt-center", targets = "_all")
        ),
        select = list(style = "single")
      )
    )
  }, server = FALSE)
  
  output[["selectedRow"]] <- renderText({
    i <- input[["dtable_rows_selected"]]
    paste0(
      "Selected row: ", 
      ifelse(is.null(i), "none", i)
    )
  })
  
}


shinyApp(ui, server)

【讨论】:

  • 很酷,对其他 Q 也有效,非常感谢你是魔术师。我发布了一个类似的带有闪亮小部件而不是 actionbutton() stackoverflow.com/questions/65729967/…
  • 据我了解,回调是关键。除了动作按钮 btn-next 之外,它可以与闪亮的小部件结合使用吗?
猜你喜欢
  • 2019-01-20
  • 2020-10-31
  • 2020-10-28
  • 2018-07-31
  • 1970-01-01
  • 2012-11-29
  • 2017-05-16
  • 1970-01-01
  • 2014-04-10
相关资源
最近更新 更多