Home > OS >  use renderUI to change the order of inputs on page
use renderUI to change the order of inputs on page

Time:09-22

I have a data entry form that users will use to enter wildlife capture data from paper data sheets. The paper sheets have many of the same fields (age, weight, sex, for example), but not all the same (for example, some have chest_girth, and others don't). The sheets are also set up in a different order, and the shiny form MUST match the exact order of the fields on the paper sheet.

I currently have a series of uiOutput/renderUI pairs that show inputs depending on what species the user selects from a dropdown. Because most of the species have the same data collected, and this data will all go into the same table, I would like to use one input for all species (for example, input$Age rather than input$BearAge and input$ElkAge). However, as I said above, the order is different on all the sheets, so please no suggestions that I just use the same form for all species.

I know that I can use shinyjs::show() and shinyjs::hide() to change whether inputs are visible, but is there a way to change the order of existing objects based on a user input, using renderUI or something else?

It would look something like this:

library(shiny)
ui <- fluidPage(
fluidRow(
  column(3, selectInput(inputId = 'species', label = 'Species', choices = c('Elk', 'Bear', 'Deer'))),
  column(3, numericInput(inputId = 'age', label = 'Age', value = NA)),
  column(3, numericInput(inputId = 'weight', label = 'Weight', value = NA))
)

server <- function(input, output, session) {
  if (input$species == 'bear') {
    *switch the order of age and weight*
   }

CodePudding user response:

library(shiny)

ui <- fluidPage(
  fluidRow(
    column(3, selectInput(inputId = 'species', label = 'Species', 
      choices = c('Elk', 'Bear', 'Deer'))),
    uiOutput("inputs_UI")
  )
)

server <- function(input, output, session) {
  output$inputs_UI <- renderUI({
    if (input$species == 'Bear') {
      tagList(
        column(3, numericInput(inputId = 'age', label = 'Age', value = NA)),
        column(3, numericInput(inputId = 'weight', label = 'Weight', value = NA))
      )
    } else {
      tagList(
        column(3, numericInput(inputId = 'weight', label = 'Weight', value = NA)),
        column(3, numericInput(inputId = 'age', label = 'Age', value = NA))
      )
    }
  })
   
}   

shinyApp(ui, server)
  • Related