Reputation: 480
I am trying to create a action button to all rows in the datatable (This is just a sample. But actual table contains lots of rows). For, I have hard coded the observe event . Since I am facing some issues here. The output I am getting now is only when clicked on first row action button, the observe event is triggering but I need this trigger to happen when clicked on all rows. (Basically a for loop)
library(shiny)
library(shinydashboard)
library(DT)
library(glue)
number_compare <- data.frame(replicate(2, sample(1:100, 10, rep=TRUE)))
sidebar <- dashboardSidebar()
body <- dashboardBody(
fluidRow(box(width = 12, solidHeader = TRUE,
DTOutput("example_table"))
)
)
ui <- dashboardPage(dashboardHeader(title = "Example"),
sidebar,
body
)
server <- function(input, output) {
number_compare <- number_compare %>% mutate(rn = row_number(), button = glue::glue(HTML('<button id="button{rn}" type="button" class="btn btn-default action-button">Ask a question</button>')))
output$example_table <- DT::renderDT({
datatable(
number_compare,
escape = FALSE
,options=list(preDrawCallback=JS(
'function() {
Shiny.unbindAll(this.api().table().node());}'),
drawCallback= JS(
'function(settings) {
Shiny.bindAll(this.api().table().node());}')))
})
observeEvent(input[[paste0("button",number_compare["rn"][1,])]],{
print("Cleicked")
})
}
shinyApp(ui, server)
Upvotes: 1
Views: 344
Reputation: 21287
You can use lapply
to meet your needs. One way to do it is
lapply (1:nrow(number_compare), function(i) {
observeEvent(input[[paste0("button",i)]],{
print("Clicked")
})
})
Another way to do is
observeEvent({
lapply (1:nrow(number_compare), function(i) {input[[paste0("button",i)]]})
}, {
print("Clicked")
})
Depending on your use case, one of these two methods could be more useful.
Upvotes: 1
Reputation: 462
According to the docs, observeEvent()
eventExpr A (quoted or unquoted) expression that represents the event; this can be a simple reactive value like input$click, a call to a reactive expression like dataset(), or even a complex expression inside curly braces
Try this:
observeEvent({
for (...) {
input[[...]]
}
}, {
print("Cleicked")
})
Upvotes: 1