Is it possible to add tickboxes in a DT datatable?

余生颓废 提交于 2019-12-11 03:02:42

问题


I would like to ask if it is possible to add a column with tickboxes in a DT datatable. I tried to use rep(TRUE,5) which works for rhandsontable but not for DT.

library(DT)
datatable(
data.frame(Sel. = rep(TRUE,5),
           Label=paste("Test",as.integer(1:5)),
           Marg=rep(5),
           Avail.=as.integer(rep.int(5,5)),
           Sel =as.integer(rep.int(5,1)),
           stringsAsFactors = FALSE))

回答1:


Yes, it's possible.

We can use the datatable extension Select for that (see here for details).

Here is a minimal RMarkdown example:

---
title: "Untitled"
output: html_document
---

```{r}
library(DT)
library(tidyverse)
datatable(
    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")))
```

This produces

A few comments:

  1. We load the Select extension through extensions = "Select". See here for details on potential compatibility issues.

  2. We add row numbers as a new column, and then set all row numbers to empty strings ""; this is a bit hack-y, but if we leave row names (=row numbers) as they are they will show up along-side the checkboxes. I found creating a new empty column, and then setting rownames = FALSE ensures that we have only check-boxes in the empty column. orderable = FALSE in columnDefs then ensures that this column is not sortable.



来源:https://stackoverflow.com/questions/51275605/is-it-possible-to-add-tickboxes-in-a-dt-datatable

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