Cauchy
Cauchy

Reputation: 1747

R Shiny: Is there a way to check if a button is disabled using shinyjs package?

Is there a way to check if a download button is disabled using the shinyjs R package? I want to use shinyjs or something similar because they have very easy syntax. This is my package:

server.R:

library(shiny)
library(shinyjs)
library(shinyBS)

shinyServer(function(input, output) {

  observe({

    shinyjs::disable("download1")

    if(shinyjs::is.disabled("download1")){ ## This is what I am trying to do
      # Do something
    }

  })

})

ui.R

shinyUI(fluidPage(

    downloadButton("download1")

))

Upvotes: 2

Views: 1643

Answers (1)

DeanAttali
DeanAttali

Reputation: 26323

Not directly (well, not easily*).

Buttons can only be disabled when you decide to disable them, so you can have some sort of a reactive variable that holds whether or not the button should be disabled, and whenever you disable the button, you also change the value of that variable. In order to make sure they stay in sync, every time you want to disable the button you can set the variable to mirror that, and then you can use shinyjs::toggleState(condition = variable) so that the disabled state will mirror what the variable says.

Example code to illustrate what I mean:

library(shiny)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  numericInput("num", "When divisible by 3, disable the button", 1),
  actionButton("btn", "button")
)

server <- function(input, output, session) {
  values <- reactiveValues(disable = FALSE)
  observe({
    values$disable <- (input$num %% 3 == 0)
  })
  observe({
    shinyjs::toggleState("btn", condition = !values$disable)
  })
}

shinyApp(ui = ui, server = server)

In this app, whenever you want to disable the button, simply set values$disable to FALSE and to enable the button set it to TRUE. To check if the button is currently on or off at any point in time, you can look at the value of values$disable.

*I'm guessing that you wanted a more direct approach to ask the app a question in real time "hey shiny, is button X currently disabled?". You can do that, but it would involve writing custom javascript code to check for the button state, and for custom code to ask javascript that question and to listen for its response. This would work and be guaranteed to be correct, but it's likely overkill for most cases.

Upvotes: 4

Related Questions