rshinydt

Adding regular button to datatable


I use datatable in my shiny app. I want to add a button close to the search button. When I click on the button I want to call the function: observeEvent(input[["btn"]]. This is my code:

   DT::renderDataTable(rownames = FALSE,                         
                               DT::datatable(my_df,extensions = 'Buttons',  
                  options = list(info  = FALSE, paging = FALSE, 
                                 dom='Bfrtip', buttons= list('copy')
                                  )))

It's looks great, but instead of the copy button I want a regular button that calls this function: observeEvent(input[["btn"]]. Do you have any idea how can I do it?


Solution

  • Let's define a custom button.

    Change the button label by text, change the shiny input ID in setInputValue, change mydf_btn to whatever you want.

    library(shiny)
    
    ui <- fluidPage(
      DT::DTOutput("mydf")
    )
    
    server <- function(input, output, session) {
        output$mydf <- DT::renderDataTable(                       
                            DT::datatable(
                                iris,extensions = 'Buttons', rownames = FALSE,  
                                options = list(
                                info  = FALSE, paging = FALSE, dom='lfBrtip', 
                                buttons= list(
                                    list(
                                        extend = 'collection',
                                        text = 'My Action',
                                        action = DT::JS(
                                        "function() {
                                            var node = this[0].node;
                                            var value = $(node).attr('data-value') || 0;
                                            value ++;
                                            $(node).attr('data-value', value);
                                            Shiny.setInputValue('mydf_btn', value, {priority: 'event'});
                                        }"
                                        )
                                    )
                                )
                              )
                            )
        )
        observe(print(input$mydf_btn))
    }
    
    shinyApp(ui, server)
    

    enter image description here