在R Shiny中使用insertUI和removeUI打印下拉列表中的选定值

ztmd8pv5  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(126)

我试图从下拉列表中打印所选的值,可以通过下面的简单代码实现:

library(shiny)

ui <- fluidPage(
  tagList(
    selectInput(
      inputId = "test",
      label = "Test",
      choices = c("Test1", "Test2", "Test3"),
      selected = NULL),
    uiOutput("text")
  )
)

server <- function(input, output, session) {
  output$text <- renderText({
    req(input$test)
    
    input$test
  })
}

shinyApp(ui, server)

但我尝试做同样的行为,但使用insertUI和removeUI函数从shiny.像它将删除以前选择的值,并将插入新的值.
有什么办法可以做到这一点吗?

kcwpcxri

kcwpcxri1#

library(shiny)

ui <- fluidPage(
  selectInput("dropdown", "Select a value:", choices = c("A", "B", "C")),
  div(id = "ui_output")
)

server <- function(input, output, session) {
  observeEvent(input$dropdown, {
    # Insert a new UI element
    insertUI(
      selector = "#ui_output",
      where = "beforeBegin",
      ui = div(
        class = "new_element",
        verbatimTextOutput("selected_value")
      )
    )
  })
  
  # Print the selected value in the new UI element
  output$selected_value <- renderText({
    input$dropdown
  })
  
  # Remove the UI element when the "Remove" button is clicked
  observeEvent(input$remove_button, {
    removeUI(selector = ".new_element")
  })
}

shinyApp(ui, server)

相关问题