Skip to content

Instantly share code, notes, and snippets.

@ncarchedi
Last active May 13, 2019 03:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ncarchedi/2ef57039c238ef074ee7 to your computer and use it in GitHub Desktop.
Save ncarchedi/2ef57039c238ef074ee7 to your computer and use it in GitHub Desktop.
Dynamically append arbitrary number of inputs (Shiny)
library(shiny)
shinyServer(function(input, output) {
# Initialize list of inputs
inputTagList <- tagList()
output$allInputs <- renderUI({
# Get value of button, which represents number of times pressed (i.e. number of inputs added)
i <- input$appendInput
# Return if button not pressed yet
if(is.null(i) || i < 1) return()
# Define unique input id and label
newInputId <- paste0("input", i)
newInputLabel <- paste("Input", i)
# Define new input
newInput <- selectInput(newInputId, newInputLabel, c("Option 1", "Option 2", "Option 3"))
# Append new input to list of existing inputs
inputTagList <<- tagAppendChild(inputTagList, newInput)
# Return updated list of inputs
inputTagList
})
})
library(shiny)
shinyUI(pageWithSidebar(
# Application title
headerPanel("Dynamically append arbitrary number of inputs"),
# Sidebar with a slider input for number of bins
sidebarPanel(
uiOutput("allInputs"),
actionButton("appendInput", "Append Input")
),
# Show a plot of the generated distribution
mainPanel(
p("The crux of the problem is to dynamically add an arbitrary number of inputs
without resetting the values of existing inputs each time a new input is added.
For example, add a new input, set the new input's value to Option 2, then add
another input. Note that the value of the first input resets to Option 1."),
p("I suppose one hack would be to store the values of all existing inputs prior
to adding a new input. Then,", code("updateSelectInput()"), "could be used to
return inputs to their previously set values, but I'm wondering if there is a
more efficient method of doing this.")
)
))
@markusdumke
Copy link

Really like this Gist! 👍
Did you find a solution to the problem that inputs are resetted when a new input is appended?

@billdenney
Copy link

billdenney commented Apr 12, 2018

Thanks!

For the input reset issue, I did something where I look in the input and see if the value exists, if so, use it. If not, use a default.

input_value <- "Option 1"
if (newInputId %in% names(input)) {
  input_value <- input[[newInuptId]]
}
selectInput(newInputId, newInputLabel, c("Option 1", "Option 2", "Option 3"), value=input_value)

@motin
Copy link

motin commented Sep 3, 2018

@markusdumke, @billdenney: Thanks for this example, question and answer. A working version of the gist (without the reset problem) can be found here: https://gist.github.com/motin/0d0ed0d98fb423dbcb95c2760cda3a30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment