Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

shiny

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 value, e.g. input$radio should be reset to NULL (as in the beginning). My approach in the server-file was as follows:

observeEvent(input$Next, {
   updateRadioButtons(session, "choice", label = "", choices = list("A" = 1, "B" = 2, "C" = 3), selected = FALSE)
})

This works fine for let's call it the layout. Each time I press the button, the selection from before is not shown anymore. However, the input$choice (input from radio buttons) has still the same value than before. However, I'd like to reset it to NULL since I have some conditional panels following the radio buttons, which are only triggered when input$choice != null. I very much appreciate any help!

like image 1000
Patrick Balada Avatar asked Jul 13 '16 09:07

Patrick Balada


1 Answers

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)
like image 160
K. Rohde Avatar answered Oct 12 '22 12:10

K. Rohde