Hi all,
I am trying to figure out how to trigger an event on a button embedded in a data table. This is inspired by this app, https://github.com/Tychobra/shiny_crud/tree/master/traditional/shiny_app which uses modules.
Any suggestions on how I can trigger an event when one of the buttons in the table are clicked? I can get the action button to work, but the potential issue is the ids in the table will change. Is it possible to de-couple this trigger from modules used in the inpsiration app?
Any tips greatly appreciated!
Thanks
Iain
Original inspiration Javascript file
function cars_table_module_js(ns_prefix) {
$("#" + ns_prefix + "car_table").on("click", ".delete_btn", function() {
Shiny.setInputValue(ns_prefix + "car_id_to_delete", this.id, { priority: "event"});
$(this).tooltip('hide');
});
$("#" + ns_prefix + "car_table").on("click", ".edit_btn", function() {
Shiny.setInputValue(ns_prefix + "car_id_to_edit", this.id, { priority: "event"});
$(this).tooltip('hide');
});
}
Javascript file in sample app www/my_js.js
document.getElementById("my_button").onclick = function() {myFunction()};
function myFunction() {
alert("My button was clicked.");
}
Shiny app
library(shiny)
library(DT)
library(purrr)
library(shinyjs)
library(dplyr)
my_data<-tibble(report_id=seq(1:5),letter=letters[1:5])
ui <- fluidPage(
shinyjs::useShinyjs(),
DTOutput('tbl'),
actionButton('my_button','mybutton'),
tags$script(src = "my_js.js"),
)
server <- function(input, output, session) {
output$tbl = renderDT({
data<-my_data
ids<-data$report_id
actions <- purrr::map_chr(ids, function(id_) {
paste0(
'<div class="btn-group" style="width: 75px;" role="group" aria-label="Basic example">
<button class="btn btn-primary btn-sm edit_btn" data-toggle="tooltip" data-placement="top" title="Edit" id = ', id_, ' style="margin: 0"><i class="glyphicon glyphicon-pencil"></i></button>
</div>'
)
})
data_to_display<- data%>%mutate(actions=actions)%>%select(actions,everything())
DT::datatable(
data_to_display,
selection = 'none',
filter = 'top',
rownames = FALSE,
escape = FALSE,
class = "compact stripe row-border nowrap",
options = list(
dom = 't',
columnDefs = list(list(width = '75px', targets = c(0))),
order = list(list(1, 'desc')),
scrollX = TRUE)
)
},server=TRUE)
}
shinyApp(ui, server)