0

i would like to remove the initial value (selected=) from selectizeInput when the user click on the widget.

Here is a sample code:

library(shiny)
library(dplyr)

ui= fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl", 
                     choices= NULL, 
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())
}

shinyApp(ui, server)

Just a bit of explanation on base of sample code:

The initial selected value in selectizeInput "cyl" is 4. When the user press on this widget, i would like that the value 4 is removed and the selected option is cleared. Any ideas?

*I have used the function updateSelectizeInput in server because in my shiny app choice selection is very big leading to too long loading time

Mal_a
  • 3,670
  • 1
  • 27
  • 60

1 Answers1

5

You can use shinyjs::onclick to call updateSelectizeInput when the user clicks on the selectize field, eg:

library(shiny)
library(dplyr)
library(shinyjs)

ui= fluidPage(
  useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl", 
                     choices= NULL, 
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())

  onclick("cyl", {
    updateSelectizeInput(session, "cyl", selected = "")
  })
}

shinyApp(ui, server)
cno
  • 645
  • 4
  • 14