firmo23
firmo23

Reputation: 8444

Display the number of rows of a datatable that are selected by tickboxes in a shiny app

I have a simple shiny app.

#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
               uiOutput("tex2")

              ),
             mainPanel(
               DT::dataTableOutput("hot3")

             )
           )))
           #server.r
library(shiny)
library(DT)
library(tidyverse)
server <- function(input, output,session) {
  output$tex2<-renderUI({
    numericInput("text2","Rows selected",
                 value = 1,
                 min=1
    )
  })



  output$hot3 <-DT::renderDataTable(
    iris%>% rowid_to_column("Row") %>% mutate(Row = ""),
    rownames = FALSE,
    extensions = "Select",
    options = list(
      columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
      select = list(style = "os", selector = "td:first-child")),
    selection=list(mode="single")


  )

}

What I need to do is display the number of rows selected in the datatable in the numericInput() in the sidebarPanel. This number is already displayed under the table but I would like to have it in the numericInput() as well. If I want to select multiple items, I need to keep the command key pressed on my Mac. On a Windows machine it should be the control key I believe. Or use shift to select multiple adjacent items.

Upvotes: 0

Views: 803

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50718

Here is a minimal example using an RMarkdown document with a shiny backend to show how to get the number of selected rows.

---
title: "Untitled"
output: html_document
runtime: shiny
---

```{r echo=FALSE}
library(DT)
library(tidyverse)
dataTableOutput("irisTable")
output$irisTable <- renderDataTable(
    iris %>% rowid_to_column("Row") %>% mutate(Row = ""),
    rownames = FALSE,
    extensions = "Select",
    options = list(
        columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
        select = list(style = "multi", selector = "td:first-child")
        ))

p("Selected rows are...")
renderText(input$irisTable_rows_selected)
```

enter image description here

Please note that in comparison to my answer to your previous post, I've changed the select.style behaviour to select = list(style = "multi", selector = "td:first-child"); this allows you to select multiple entries by single-clicking on rows (instead of having to hold the Command/Ctrl key).

Upvotes: 1

Related Questions