简体   繁体   中英

Reset and clear out Shiny text output using reset button

I am creating a calculator that takes multiple inputs and prints the calculation after clicking 'Calculate'. I also provide a reset button that successfully resets the input values back to their default.

The reset button should also clear the previously printed output (basically I want it to look exactly like it did when you first open the app).

Below is a simplified and still functioning example of the calculator.

library(shiny)
library(shinyjs)


ui <- fluidPage(
  useShinyjs(),
  div(id="form",
  sidebarLayout(
    sidebarPanel(
      numericInput("x","X",0),
      numericInput("y","Y",0)
    ),
    mainPanel(
      br(),
      column(width=6,actionButton("calc", "Calculate")),
      column(width=6,actionButton("reset", "Reset")), 
      br(),br(),br(),
      textOutput("sum"))
  )
))


# Define the server logic
server <- function(input, output) {
  output$sum <- renderText({
    req(input$calc)
    isolate(paste("X + Y =", input$x + input$y))
  })

  observeEvent(input$reset, {
    reset("form")
      })
}

# Run the application
shinyApp(ui = ui, server = server)

I have tried a few approaches offered on here for other, seemingly similar questions but I haven't managed to get them to work. I would offer some examples of what I've done but I've lost track of them at this point and I'm hoping there's just some obvious, simple answer that I've overlooked. I'm fairly new to Shiny, though, so details of why a possible answer works would also be appreciated!

Edited to based on comments.

I think the simplest observer would be:

# two observers
server <- function(input, output) {

  observeEvent(input$calc, {
    output$sum <- renderText({
      req(input$calc)
      isolate(paste("X + Y =", input$x + input$y))
    })
  })


  observeEvent(input$reset, {
    output$sum <- renderText({

    })
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM