purple1437
purple1437

Reputation: 313

How to set up actionButton() or actionBttn() to clear all selections in pickerInput()

When I click on the Action Button, I would like to clear everything: both the output and the selections in the picketInput() (input$engine and input$cylinder in the code below). For consistency if I can do it with shinyWidget's actionBttn, that will be great as well.

library(shiny)
library(shinyWidgets)
df <- mtcars

ui <- fluidPage(
  sidebarPanel(
    pickerInput("engine", "Select engine:", choices = unique(df$vs),
      options = list(
        `actions-box` = TRUE), 
      multiple = TRUE
    ),
    pickerInput("cylinder", "Select cylinder:", choices = unique(df$cyl),
      options = list(
        `actions-box` = TRUE), 
      multiple = TRUE
    ),
    actionButton("reset", "Clear Selection"),
  ),
  mainPanel(
    textOutput("results")
  )
)

server <- function(input, output, session) {
  data <- reactiveValues()
  
  observeEvent(input$cylinder, {
    tmp <- df
    tmp1 <- tmp[tmp$vs %in% input$engine, ]
    tmp2 <- tmp1[tmp1$cyl %in% input$cylinder, ]
    data$tmp2 <- tmp2
  })

  output$results <- renderText({
    if(is.null(data$tmp2)) return()
    print(row.names(data$tmp2))
  })
  
  observeEvent(input$reset, {
    updatePickerInput(session, "engine", NULL)
    updatePickerInput(session, "cylinder", NULL)
    data$tmp2 <- NULL
  })  
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 278

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33442

You'll have to respect the order of updatePickerInput's parameters or name them. Your above approach would have updated the label.

Please see ?updatePickerInput and check the following:

library(shiny)
library(shinyWidgets)
library(datasets)

DF <- mtcars

ui <- fluidPage(
  sidebarPanel(
    pickerInput("engine", "Select engine:", choices = unique(DF$vs),
                options = list(
                  `actions-box` = TRUE), 
                multiple = TRUE
    ),
    pickerInput("cylinder", "Select cylinder:", choices = unique(DF$cyl),
                options = list(
                  `actions-box` = TRUE), 
                multiple = TRUE
    ),
    actionBttn("reset", "Clear Selection"),
  ),
  mainPanel(
    textOutput("results")
  )
)

server <- function(input, output, session) {
  data <- reactiveValues()
  
  observeEvent(input$cylinder, {
    tmp <- DF
    tmp1 <- tmp[tmp$vs %in% input$engine, ]
    tmp2 <- tmp1[tmp1$cyl %in% input$cylinder, ]
    data$tmp2 <- tmp2
  })
  
  output$results <- renderText({
    req(data$tmp2)
    row.names(data$tmp2)
  })
  
  observeEvent(input$reset, {
    updatePickerInput(session, inputId = "engine", selected = "")
    updatePickerInput(session, inputId = "cylinder", selected = "")
    data$tmp2 <- NULL
  })  
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions