Tristan Tran
Tristan Tran

Reputation: 1513

Toggle (i.e. hide/unhide) rows in datatable

Is there a way to implement this: I have got a datatable displayed and I would like to toggle a particular row if a row index is selected and a toggle button is clicked. I just want to hide the row, not deleting from the datatable completely. I have got the ui as following. How to implement the server side?

library(shiny)
library(DT)

data <- data.frame(
    Name = c("Andy", "Bob", "Chad"),
    Job = c("Clerk", "Pilot", "Electrician")
)

ui <- fluidPage(
    
    box(id = "myBox", title = NULL, 
        selectInput(inputId = "row_index", label = "Row to Toggle", choices = c(1,2,3))
    ),
    actionButton(inputId = "button", label = "Show/Hide"),
    DT::dataTableOutput(('DTOut'))
)

server <- function(input, output) {
    
    output$DTOut <- DT::renderDataTable({
        data
    })
}
shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 1159

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84599

Here is a way. It requires to have a column of row indices at the first position. If you don't want to display the row indices, then add this column and hide it.

library(shiny)
library(DT)

initComplete <- JS(
  "function(settings, json) {",
  "  var table = this.api();",
  "  var nrows = table.rows().count();",
  "  $('#button').on('click', function() {",
  "    var nrows_filtered = table.rows({search:'applied'}).count();",
  "    if(nrows_filtered === nrows) {",
  "      var selection = $('select[id=row_index] option').val();",
  "      var rowsToShow = [];",
  "      for(var i = 1; i <= nrows; ++i) {",
  "        if(i != selection) rowsToShow.push('^' + i + '$');",
  "      }",
  "      var regex = '(' + rowsToShow.join('|') + ')';",
  "      table.column(0).search(regex, true).draw();",
  "    } else {",
  "      table.columns().search('').draw();",
  "    }",
  "  });",
  "}"
)

data <- data.frame(
  Name = c("Andy", "Bob", "Chad"),
  Job = c("Clerk", "Pilot", "Electrician")
)

ui <- fluidPage(
  
  wellPanel(id = "myBox", 
      selectInput(inputId = "row_index", label = "Row to Toggle", choices = c(1,2,3))
  ),
  actionButton(inputId = "button", label = "Show/Hide"),
  DTOutput("DTOut")
  
)

server <- function(input, output) {
  
  output$DTOut <- renderDT({
    datatable(data, options = list(initComplete = initComplete))
  })
  
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions