I have an RShiny a dropdow (a selectInput object) and I would like to be able to switch between options using a keyboard shortcut.
For my purposes the best option would be to have the key combination loop through the available options.
So far, I've managed to assign individual keys to individual options in the dropdow, using the selectize. This is the piece of code I am adding to the fluidPage:
tags$script(HTML("$(function(){
$(document).keyup(function(e) {
if(e.which == 49){
var selectized = $('#selector_name').selectize();
selectized[0].selectize.setValue(1);
}
});
})"))
What I was trying to do a switch statement inside the innermost if, like this:
if <current_value> = 1 {
selectized[0].selectize.setValue(1);
} else if <current_value> = 2 {
...
}
However I don-t know how to access <current_value>.
In addition, the code above assigns a signle keystroke to the event, but I would really prefer using a combination of keys, such as SHIFT + D.
Edit: added minimum working example
library(shiny)
ui <- fluidPage(
# keyboard shortcuts for selectors
# Key 1 for option 1
tags$script(HTML("$(function(){
$(document).keyup(function(e) {
if(e.which == 49){
var selectized = $('#dropdown').selectize();
selectized[0].selectize.setValue(1);
}
});
})")),
# key 2 for option 2
tags$script(HTML("$(function(){
$(document).keyup(function(e) {
if(e.which == 50){
var selectized = $('#dropdown').selectize();
selectized[0].selectize.setValue(2);
}
});
})")),
# define the selector
selectInput(inputId = "dropdown",
label = "Dropdown",
choices = c(1,2),
selected = 0)
)
server <- function(input, output, session) {}
shinyApp(ui, server)
There may be a way to do it purely in javascript (I'm all ears!) but an alternative is to catch the key press in javascript but update the selected entry in R:
library(shiny)
choices <- c(1, 2, 3)
ui <- fluidPage(
tags$script(HTML("
$(document).on('keydown', function(e) {
if( e.shiftKey && e.key === 'D'){
Shiny.onInputChange('dKey', new Date().getTime());
}
})
")),
selectInput(inputId = "dropdown",
label = "Dropdown",
choices = choices,
selected = 0)
)
server <- function(input, output, session) {
observeEvent(input$dKey, {
index <- match(input$dropdown, choices)
if (index < length(choices)){
next_index <- index + 1
} else {
next_index <- 1
}
updateSelectInput(session, "dropdown", selected = choices[next_index])
})
}
shinyApp(ui, server)