Can I update the label of a downloadButton in shiny?

Viewed 56

I have a web app that does some transformation and allows the user to control it, and then download the results. I want to update the label on the button so that the user knows the content that he will download.

Basically,

ui <- fluidPage(
  checkboxInput("use_avg", "Use averages"),
  actionButton("b1", "Download"),

)

server <- function(input, output, session) {
   observeEvent(input$use_avg, {
    if (input$use_avg == TRUE) {
      updateActionButton(inputId = "b1", label = "Download averages")
    } else {
      updateActionButton(inputId = "b1", label = "Download")
    }
  })
}

Is there a way to do this with a downloadButton, or a way to use actionButton with downloadHandler?

2 Answers

This option would work with either the downloadButton() or the actionButton(). In the ui side, I made a uiOutput(), which changes the button depending on the checkboxInput(). It isn't exactly changing the label, but rather creating a different button depending on the checkbox.

**Edited to show the use of toggleState() with this solution, disabling or enabling based on a checkbox as asked for in the comment.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  checkboxInput("use_avg", "Use averages"),
  uiOutput("D1"),
  checkboxInput("Disable", 'toggleState checkbox?', value = T)
)

server <- function(input, output, session) {
  output$D1<-renderUI({
    if (input$use_avg == TRUE) {
      downloadButton(outputId = "b1", label = "Download averages")
    } else {
      downloadButton(outputId = "b1", label = "Download")
    }
  })
  observeEvent(input$Disable, {
                 toggleState("b1") 
               })
}

shinyApp(ui, server)

There is no official way to do so, but here is a workaround:

library(shiny)
library(shinyjs)
ui <- fluidPage(
    useShinyjs(),
    checkboxInput("use_avg", "Use averages"),
    downloadButton("download", "Download")
)
server <- function(input, output, session) {
    observeEvent(input$use_avg, {
        if (input$use_avg == TRUE) return(runjs('$("#download")[0].childNodes[2].nodeValue = " Download averages"'))
        runjs('$("#download")[0].childNodes[2].nodeValue = " Download"')
    })
}

shinyApp(ui, server)
Related