Shiny in R: How to set an input value to NULL after clicking on a button?

后端 未结 1 1180
庸人自扰
庸人自扰 2021-02-10 12:24

my situation is the following: I have an action button (Next) and some radio buttons. Each time, I click the action button, no radio button should be selected and the input valu

1条回答
  •  生来不讨喜
    2021-02-10 12:55

    You can overwrite the value yourself from the client (browser) side.

    There is an inbuild function that is used to assign the various values to the input variable, which is called Shiny.onInputChange. This is a JavaScript function that is used to send data (things that are selected in the browser) to the R session. This way, you can assign null (JavaScript equivalent of the R NULL) to the input variable you want, thus "resetting" it.

    Of course, you need to trigger the client side from the R server, and this is done by a customMessageHandler, that is like the counterpart to onInputChange. It installs a listener on the client side, which can handle messages you send to the client.

    Everything you need to know about those concepts can be found here.

    Below is a short example how to do this:

    library(shiny)
    
    ui <- fluidPage(
      actionButton("Next", "Next"),
      radioButtons("choice", label = "", choices = list("A" = 1, "B" = 2, "C" = 3), selected = character(0)),
      textOutput("status"),
      tags$script("
        Shiny.addCustomMessageHandler('resetValue', function(variableName) {
          Shiny.onInputChange(variableName, null);
        });
      ")
    )
    
    server <- function(input, output, session){
    
      output$status <- renderText({input$choice})
    
      observeEvent(input$Next, {
        updateRadioButtons(session, "choice", selected = character(0))
        session$sendCustomMessage(type = "resetValue", message = "choice")
      })
    }
    
    shinyApp(ui, server)
    

    0 讨论(0)
提交回复
热议问题