简体   繁体   中英

Shiny serverside suggestions according to user typing

I would like to update the choices of a pickerInput according to what the user starts typing. Similar to what happens when you start typing with Google.

在此处输入图像描述

The suggestions have to be handled serverside.

Below is my code. The problem is that what the user is typing - if it's not an existing choice - is not sent to the server. Is there a way to send what the user types?

Maybe pickerInput is not the right approach? How else could I accomplish this?

library(shiny)
library(shinyWidgets)

suggest <- function(x) {
  # would in reality send whatever the user starts typing to an API that returns suggestions
  choices <- c("Some", "One", "Suggests", "This", "According", "To", "Input")
  choices[grep(x, choices, ignore.case = T)]
}

ui <- fluidPage(
  pickerInput(inputId = "id1",
              choices = c(),
              options = list(`live-search` = T))
)

server <- function(input, output, session) {
  observe({
    req(input$one)
    updatePickerInput(session, inputId = "id1", choices = suggest())
  })
}

shinyApp(ui, server)

You can use shiny::selectizeInput() to achieve what you want:

library(shiny)

# Generate arbitrarily thousands of choices which can only be rendered 
# serverside to avoid app slowdown:
k <- expand.grid(col1 = letters, col2 = letters, col3 = LETTERS)
choices <- with(k, paste0(col1, col2, col3))

ui <- fluidPage(
  selectizeInput(
    inputId = "selector", 
    label = "Selector", 
    choices = NULL
  )
)

server <- function(input, output, session) {
  observe({
    updateSelectizeInput(
      session = session,
      inputId = "selector",
      choices = choices, 
      server = TRUE
    )
  })
}

shinyApp(ui, server)

Created on 2022-07-23 by the reprex package (v2.0.1)

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