The app below works as expected on startup and when clicking the "Next Vehicle >" actionButton
for the first time.
When I press the actionButton a second time, it selects the third vehicle as expected, but when I open the dropdown, the previously selected value "Cadillac Fleetwod" is listed first, when I would expect it to be listed second.
If I press the actionButton a third time, "Chrysler Imperial" is correctly selected, but now "Camaro Z28" is listed first, when I would expect it to be listed third. Note, "Cadillac Fleetwood" and "AMC Javelin" are correct if you ignore the first value.
If I avoid using the actionButton altogether and instead manually click every time, the ordering in the dropdown menu is as expected.
The previous value in input$vehicle
is being listed first every time when I use the actionButton. How can I prevent this from happening and have my choices for input$vehicle
be listed alphabetically when I use the button regardless of the previous value?
library(shiny)
df <- mtcars
df$vehicle <- rownames(df)
df <- df[order(df$vehicle), c("vehicle", colnames(mtcars))]
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectizeInput("vehicle",
"Select vehicle",
choices=NULL,
selected=NULL),
),
mainPanel(
actionButton("nextbut", "Next Vehicle >") ,
)
)
)
server <- function(input, output, session) {
observe({
updateSelectizeInput(session,
"vehicle",
"Select vehicle",
df$vehicle,
selected=df$vehicle[1],
server = T)
})
observeEvent(input$nextbut, {
vehicles <- df$vehicle
idx <- which(vehicles == input$vehicle)
if(idx != length(vehicles)){
updateSelectizeInput(session,
"vehicle",
label = "Select vehicle",
choices = vehicles,
vehicles[idx+1],
server=T
)
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
observeEvent(input$nextbut, {
vehicles <- df$vehicle
idx <- which(vehicles == input$vehicle)
if(idx != length(vehicles)){
updateSelectizeInput(session,
"vehicle",
label = "Select vehicle",
choices = vehicles,
vehicles[idx+1],
server=T,
options = list(
sortField = list(
field = "text",
direction = "asc"
)
)
)
}
})