问题
I am using selectizeInput in Shiny and would like to adapt this function so that only words starting with the characters entered by the user in the search field are shown in the option list. I look at the JavaScript code at: force selectize.js only to show options that start with user input and tried the following:
library("shiny")
selectList <- sapply(1:10000, function(x) paste(sample(letters, 8), collapse = ''))
ui <- fluidPage(
selectizeInput(inputId = 'mylist', label = 'Select something', choices = NULL, selected = 1),
actionButton("search", "search"), br(), br(),
textOutput("value")
)
server <- function(input, output, session) {
updateSelectizeInput(session = session, inputId = 'mylist', choices = c(Choose = '', selectList), server = TRUE,
options = list(placeholder = "Select something",
dropdownParent = 'body',
openOnFocus = FALSE,
items = c(),
score = I("function(search)
{
var score = this.getScoreFunction(search);
return function(item)
{
return item.text
.toLowerCase()
.startsWith(search.toLowerCase()) ? 1 : 0;
};
}")
)
)
getValue <- eventReactive(input$search, { return(input$mylist) })
output$value <- renderPrint({ return(getValue()) })
}
shinyApp(ui = ui, server = server)
but is does not work yet. Maybe I missed something simple, but does anybody know what should be changed in this code?
回答1:
Solution: replace item.text by item label (thanks to jcheng, RStudio Community). I restructured the code a bit:
library("shiny")
selectList <- sapply(1:100000, function(x) paste(sample(letters, 8), collapse = ''))
ui <- fluidPage(
selectizeInput(inputId = 'mylist', label = 'Select something', choices = NULL, selected = 1),
actionButton("search", "search"), br(), br(),
textOutput("value")
)
server <- function(input, output, session)
{
getScore <- function()
{
return(I("function(search)
{
var score = this.getScoreFunction(search);
return function(item)
{
return item.label
.toLowerCase()
.startsWith(search.toLowerCase()) ? 1 : 0;
};
}"
)
)
}
updateSelectizeInput(session = session, inputId = 'mylist', choices = c(Choose = '', selectList), server = TRUE,
options = list(placeholder = "Select something", dropdownParent = 'body',
openOnFocus = FALSE, items = c(), score = getScore()))
getValue <- eventReactive(input$search, { return(input$mylist) })
output$value <- renderPrint({ return(getValue()) })
}
shinyApp(ui = ui, server = server)
来源:https://stackoverflow.com/questions/52039435/force-selectize-js-only-to-show-options-that-start-with-user-input-in-shiny