Home > front end >  adding regular button to datatable - shiny app
adding regular button to datatable - shiny app

Time:09-28

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 call this function: observeEvent(input[["btn"]] any idea how can I do it?

CodePudding user response:

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

  • Related