EGM8686
EGM8686

Reputation: 1572

R Shiny Disable button and change label after clicking

I have a Shiny App that has a button that runs a quite long (around 30 minutes) routine. what I would like to do is to disable the button that calls the process once the user clicks on it and that the button can be 'clickable' again once the process finishes...

Ideally I would click on the Action Button and it gets disabled, its label changes to 'Running' and once the process ends the button is clickable again and the label goes back to 'Run Process'.

So:

  1. User clicks on an action button labeled "Run"
  2. Button changes label to "Running" and is no longer clickable
  3. Process Finishes
  4. Button is clickable again and label goes back to "Run"

Thx

Upvotes: 1

Views: 1302

Answers (2)

Stéphane Laurent
Stéphane Laurent

Reputation: 84529

That depends on what happens when you click the button. Here is an example where clicking the button runs a time-consuming plot.

library(shiny)

js <- '
$(document).ready(function(){
  $("#myplot").on("shiny:recalculating", function(){
    $("#run").prop("disabled", true).text("Running...");
  }).on("shiny:recalculated", function(){
    $("#run").prop("disabled", false).text("Run");
  });
})
'

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  br(),
  actionButton("run", "Run", class = "btn-primary btn-lg"),
  br(),
  plotOutput("myplot")
)

server <- function(input, output, session){
  
  output[["myplot"]] <- renderPlot({
    if(input[["run"]] > 0){
      x <- y <- NULL
      for(. in 1:25000){
        x <- c(x, runif(1))
        y <- c(y, runif(1))
      }
      plot(x, y)
    }
  })
  
}

shinyApp(ui, server)

enter image description here

And you can add a spinner with the shinybusy package:

library(shiny)
library(shinybusy)

js <- '
$(document).ready(function(){
  $("#myplot").on("shiny:recalculating", function(){
    $("#run").prop("disabled", true).text("Running...");
  }).on("shiny:recalculated", function(){
    $("#run").prop("disabled", false).text("Run");
  });
})
'

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  add_loading_state(
    "#myplot",
    spinner = "hourglass",
    svgSize = "100px"
  ),
  br(),
  actionButton("run", "Run", class = "btn-primary btn-lg"),
  br(),
  plotOutput("myplot")
)

enter image description here

Upvotes: 0

Radvvan
Radvvan

Reputation: 155

Basic shiny has update functions, such as updateActionButton(). You can use it to update the label:

updateActionButton(inputId = "run_button", label = "Running...")

As for disabling and enabling buttons, look into shinyjs library - it provides functions for a lot of this sort of stuff.

Upvotes: 2

Related Questions