SavedByJESUS SavedByJESUS - 17 days ago 8
R Question

Show/hide inputs based on numericInput and actionButton

The shiny app has the following elements:


  • one
    numericInput
    field with values between 0 and 3

  • one
    uiOutput
    which contains three hidden
    textInput
    fields

  • one
    actionButton



What I would like to achieve is to
show
the hidden
textInput
fields after a button click. The number of fields shown depends on the number selected in the
numericInput
The fully functional code below succeeds in doing that; however, there is an issue I can't seem to find a solution to. For example, if I select
3
and click the button, the 3 hidden
textInput
fields appear (yay!), but then if I immediately select a number lower than
3
and click the button, the unwanted fields still remain. How can I achieve that? Thanks

library(shiny)
library(shinyjs)

ui <- fluidPage(

useShinyjs(),

numericInput(inputId = "num", label = "How many inputs do you want to show?", value = 1, min = 1, max = 3),

uiOutput(outputId = "out"),

actionButton(inputId = "go", label = "Click me!")
)

server <- function(input, output){

output$out <- renderUI({
numinputs <- lapply(1:3, function(i){
textInput(inputId = paste0("txt", i), label = paste0("Text input ", i))
})
shinyjs::hidden(numinputs)
})

observeEvent(eventExpr = input$go, handlerExpr = {
for(i in seq(input$num)){
shinyjs::show(id = paste0("txt", i))
}
})
}

shinyApp(ui = ui, server = server)

Answer

This code is similar to @SBista 's but without the nout variable.

library(shiny)
library(shinyjs)

ui <- fluidPage(

    useShinyjs(),

    numericInput(inputId = "num", label = "How many inputs do you want to show?", value = 1, min = 1, max = 3),

    uiOutput(outputId = "out"),

    actionButton(inputId = "go", label = "Click me!")
)

server <- function(input, output){
    output$out <- renderUI({
        numinputs <- lapply(1:3, function(i){
            textInput(inputId = paste0("txt", i), label = paste0("Text input ", i))
        })
        shinyjs::hidden(numinputs)
    })

    observeEvent(eventExpr = input$go, handlerExpr = {
        n <- seq(length.out = as.numeric(input$num))
        lapply(seq(3), function(i) {
            if(i %in% n) {
                shinyjs::show(id = paste0("txt", i))
            } else{
                shinyjs::hide(id = paste0("txt", i))
            }
        })
    })
}

shinyApp(ui = ui, server = server)
Comments