R shiny datatable link to another tab

僤鯓⒐⒋嵵緔 提交于 2019-12-05 14:56:01

I am not so deeply involved with DT but this JS callback function works:

function(settings, json) {
  var table = this.DataTable();
  table.on("click.dt", "tr", function() {
    Shiny.onInputChange("rows", table.row( this ).index());
    var tabs = $(".tabbable .nav.nav-tabs li a");
    $(tabs[1]).click();
  });
}

MRE:

library(shiny)
library(ggplot2)  # for the diamonds dataset
library(htmlwidgets)

ui <- fluidPage(
  title = "Examples of DataTables",
  sidebarLayout(
    sidebarPanel(
      conditionalPanel(
        'input.dataset === "diamonds"',
        checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                           names(diamonds), selected = names(diamonds))
      ),
      conditionalPanel(
        'input.dataset === "mtcars"',
        helpText("Click the column header to sort a column.")
      ),
      conditionalPanel(
        'input.dataset === "iris"',
        helpText("Display 5 records by default.")
      )
    ),
    mainPanel(
      tabsetPanel(
        id = 'dataset',
        tabPanel("diamonds", DT::dataTableOutput("mytable1")),
        tabPanel("mtcars", DT::dataTableOutput("mytable2")),
        tabPanel("iris", DT::dataTableOutput("mytable3"))
      )
    )
  )
)


jss <- '
function(settings, json) {
  var table = this.DataTable();
  table.on("click.dt", "tr", function() {
    Shiny.onInputChange("rows", table.row( this ).index());
    var tabs = $(".tabbable .nav.nav-tabs li a");
    $(tabs[1]).click();
  });
}'

server <- function(input, output) {

  # choose columns to display
  diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
  output$mytable1 <- DT::renderDataTable({
    DT::datatable(diamonds2[, input$show_vars, drop = FALSE], options = list(initComplete = JS(jss)))
  })

  # sorted columns are colored now because CSS are attached to them
  output$mytable2 <- DT::renderDataTable({
    DT::datatable(mtcars, options = list(orderClasses = TRUE))
  })

  # customize the length drop-down menu; display 5 rows per page by default
  output$mytable3 <- DT::renderDataTable({
    DT::datatable(iris, options = list(initComplete = JS(jss)))})
}

shinyApp(ui, server)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!