Add dynamic UI element to R shiny data table
I am creating a datasheet with some results. I would like the user to be able to click on a specific line, for example to show details. The following setting works:
ui.R
library(DT)
shinyUI({
basicPage(
actionButton("compute", "Compute"),
tags$div(id="blah", class="shiny-input-radiogroup",
dataTableOutput( "results" )
),
tags$h1(textOutput( "foo" ))
)
})
server.R
library(DT)
server.fun <- function(input, output) {
output$foo <- renderText({
input$blah
})
output$results <- renderDataTable({
if(input$compute) {
results <- data.frame(ID=1:10, contents=letters[1:10])
results$checkbox <- sprintf( '<input type="radio" name="blah" value="%d"/>', 1:10 )
datatable(results, escape=FALSE)
} else {
NULL
}
})
}
When you click on the switch, the action is performed (the line number is displayed at the bottom). It's nice and demonstrates what I want to achieve. However, I would like to have a normal action button, not a radio button. The following code doesn't work, my question is, how can I get it to work?
ui.R
library(DT)
shinyUI({
basicPage(
actionButton("compute", "Compute"),
dataTableOutput( "results" ),
tags$h1(textOutput( "foo" ))
)
})
server.R
library(DT)
server.fun <- function(input, output) {
output$foo <- renderText({
input$blah
})
output$results <- renderDataTable({
if(input$compute) {
results <- data.frame(ID=1:10, contents=letters[1:10])
results$checkbox <-
sprintf( '<button id="blah" type="button" class="btn btn-default action-button" value="%d">Do</button>', 1:10 )
datatable(results, escape=FALSE)
} else {
NULL
}
})
}
+3
source to share
1 answer
If anyone needs this, I found a way to make it work with an action button inside a table. In this case, when '?' and a warning message is displayed. Here's the code:
output$factorsTable = DT::renderDataTable(
DT::datatable({
factorName <- c('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5', 'Factor 6', 'Factor 7', 'Factor 8', 'Factor 9', 'Factor 10')
factorValues <- c('0.1','0.2','0.3','0.4','0.5','0.6','0.7','0.8','0.9','1')
helpBtn <- '<button><b>?</b></button>'
helpButton <- c(helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn)
factors.data <- data.frame(factorName, factorValues,helpButton)
factors.data},
colnames = c('Factor','Value',,'Help'),
escape = FALSE,
rownames = FALSE,
selection= 'single',
options = list( searching=FALSE, paging =FALSE,
columnDefs = list(
list(
targets=4,
render=JS(
"function(data, type, full) {",
"return '<a class=\"btn btn-primary btn-sm\" onclick=\"alert(\\''+ full[0] +'\\')\" href=#/' + '>' + '?' + '</a>';",
"}"
)
))
),
class = "display",
callback = JS('table.page(0).draw(false);')
)
)
0
source to share