Search code examples
shinyshiny-servershinydashboard

In RShiny ui, how to dynamic show several numericInput based on what you choose


My code is here:

ui.R

shinyUI(fluidPage(

  # Copy the line below to make a select box 
  selectInput("select", label = h3("Select box"), 
              choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3), 
              selected = 1),
  numericInput("value",label="value", value=100),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

))

server.R

server=shinyServer(function(input, output) {
output$inputs=renderUI({
if(input$select =="1"){
  numericInput(inputId = paste0("value",1),"1",100)

} else if(input$select=="2"){
    numericInput(inputId ="value","value",100),
    numericInput(inputId ="value","value",200),
    numericInput(inputId ="value","value",300)
  }

})

# You can access the value of the widget with input$select, e.g.
output$value <- renderPrint({ input$select })

})

This is a very simple case and the ui is like: enter image description here

What I expect is that if I select "Choice 2", ui would give me this: enter image description here

So how I can achieve my expectation?


Solution

  • You have to render it on server side

    Example

    Show 1 ,2 and 3 input based on select

    library(shiny)
    ui=shinyUI(fluidPage(
      
      # Copy the line below to make a select box 
      selectInput("select", label = h3("Select box"), 
                  choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3), 
                  selected = 1),
      uiOutput("inputs"),
      
      hr(),
      fluidRow(column(3, verbatimTextOutput("value")))
      
    ))
    
    
    server=shinyServer(function(input, output) {
      output$inputs=renderUI({
        lapply(1:input$select,function(i){
          numericInput(inputId = paste0("value",i),paste0("value",i),100)
        })
      })
      
      # You can access the value of the widget with input$select, e.g.
      output$value <- renderPrint({ input$select })
      
    })
    
    shinyApp(ui,server)
    

    There i use simple logic : if your choise 1 so one input redered, 2-- two inputs e.t.c

    Update

    Hard code example

    server=shinyServer(function(input, output) {
      output$inputs=renderUI({
        if(input$select==1){
          numericInput(inputId = paste0("value1"),paste0("value1"),100)
        }else if( input$select==2){
          list(
            numericInput(inputId = paste0("value1"),paste0("value1"),100),
            numericInput(inputId = paste0("value2"),paste0("value2"),200),
            numericInput(inputId = paste0("value3"),paste0("value3"),500)
            
          )
        }else if (input$select==3){
          numericInput(inputId = paste0("value1"),paste0("value1"),100)
        }
        
      })
      
      # You can access the value of the widget with input$select, e.g.
      output$value <- renderPrint({ input$select })
      
    })