Skip to content

Instantly share code, notes, and snippets.

@jdtrat

jdtrat/app.R Secret

Last active March 4, 2021 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdtrat/9dca88e03e33f495039d7d9f182c4534 to your computer and use it in GitHub Desktop.
Save jdtrat/9dca88e03e33f495039d7d9f182c4534 to your computer and use it in GitHub Desktop.
Using a custom Shiny input to insert Shiny inputs
# Create growthInput ------------------------------------------------------
growInput <- function(inputId) {
shiny::tagList(
shiny::div(class = "growInput",
id = inputId,
shiny::fluidRow(
shiny::div(id = paste0("grow_here"),
shiny::textInput(inputId = "grow_1",
label = "",
value = "Growth!",
width = "69%")
),
shiny::actionButton("make_grow",
label = "",
icon = shiny::icon("plus")
)
)))
}
# Demo Shiny App ----------------------------------------------------------
library(shiny)
ui <- fluidPage(
tags$script(
# assumes this file is within "www" subdirectory.
src = "growInput-binding.js"
),
tags$style('.growInput{border: 1px solid black; padding: 20px;}'),
growInput(inputId = "tree")
)
server <- function(input, output, session) {}
shinyApp(ui, server)
// initialize growth_number as 1 since we start with one textInput
var growth_number = 1;
var growInputBinding = new Shiny.InputBinding();
$.extend(growInputBinding, {
// find the dom element with input$id
// this becomes el downstream
find: function find(scope) {
return $(scope).find(".growInput")
},
// Get the value of the custom input
getValue: function getValue(el) {
return 'growing!'
},
subscribe: function(el, callback) {
// When the add_option button is clicked, insert another input element
$(el).find("#make_grow").on("click", function() {
// unbind all Shiny inputs
Shiny.unbindAll();
// increment the growth_number
growth_number++;
// append to the growth_placeholder a new input element
$(el).find('#grow_here').append(
'<div class=\"form-group shiny-input-container\" style=\"width:69%;\">' +
'<label class=\"control-label\" id=\"growth_' + growth_number + 'label\" for=\"growth_' + growth_number + '\"></label>' +
'<input id=\"growth_' + growth_number + '\" type=\"text\" class=\"form-control\" value=\"I grew #' + growth_number + '\"/>' +
'</div>'
);
// Bind all shiny inputs, including the newly inserted one.
Shiny.bindAll();
})
},
unsubscribe: function(el) {
$(el).off(".growInputBinding");
},
});
Shiny.inputBindings.register(growInputBinding);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment