Created
December 30, 2019 20:22
-
-
Save gadenbuie/2a2501414b929ef608f5290d9f28c926 to your computer and use it in GitHub Desktop.
dynamic Shiny input names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
library(purrr) | |
ui <- fluidPage( | |
textInput("inputId", "inputId", value = "number"), | |
helpText("Create a new input ID for the dropdown below"), | |
selectInput("number", "Renamable", choices = letters[1:5], selected = 1), | |
helpText("Notice that old inputs stick around..."), | |
verbatimTextOutput("debug"), | |
tags$script(HTML( | |
" | |
// Find the inputs | |
const inputSetter = document.getElementById('inputId') | |
const inputRenameable = document.getElementById('number') | |
// global variable for debouncing | |
let debounce = null | |
// Listen to the textInput value change in the browser | |
inputSetter.addEventListener('input', (ev) => { | |
// don't do anything if the input is changing or if the value is '' | |
clearTimeout(debounce) | |
if (!ev.target.value) return; | |
debounce = setTimeout(() => { | |
// take the value from the textInput() | |
const newInputId = ev.target.value | |
// and set the selectInput ID to the new ID | |
inputRenameable.setAttribute('id', newInputId) | |
// then tell the server what we did | |
Shiny.setInputValue(newInputId, inputRenameable.value, {priority: 'event'}) | |
}, 500) | |
}) | |
" | |
)) | |
) | |
server <- function(input, output, session) { | |
output$debug <- renderPrint({ | |
names(input) %>% | |
set_names() %>% | |
map(~ input[[.x]]) %>% | |
str() | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment