0

假设我有以下Shiny应用程序-

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    checkboxInput("checkbox", label = "Choice a value", value = TRUE),
    selectInput("variable", "Variable:",
                c("Cylinders" = "cyl",
                  "Transmission" = "am",
                  "Gears" = "gear"))
  ),
  server = function(input, output) {
    observeEvent(input$checkbox, {
            toggleState("variable")
        })
  }
)

现在我希望如果checkbox单击则始终Cylindersvariable.

使用上述方法,这不会发生。Gears目前,当用户在启用后选择其他值 ig variable,然后再次用户继续checkbox禁用variable时,选择Gears保留在 UI 中,我不想并且Cylinders每次都想立即返回到该选项variable被禁用。

任何如何实现这一点的指针都将受到高度赞赏。

bretauv's回复后更新——

他的回答适用于shiny'snative ,但如果我使用如下包selectInput()似乎不起作用-shinyWidgetspickerInput()

library(shiny)
library(shinyjs)
library(shinyWidgets)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    checkboxInput("checkbox", label = "Choice a value", value = FALSE),
    pickerInput("variable", "Variable:",
                c("Cylinders" = "cyl",
                  "Transmission" = "am",
                  "Gears" = "gear"),
                 width = "50%",
                selected = "gear")
  ),
  server = function(input, output, session) {
    observe({
            if (input$checkbox) {
                    toggleState(id = "variable")
                } else {
                    toggleState(id = "variable")
                    updatePickerInput(session = session,
                                        inputId = "variable", label = NULL,  
                                        choices = c("Cylinders" = "cyl",
                                                      "Transmission" = "am",
                                                      "Gears" = "gear"),
                                        selected = "Cylinders")
                }
            })
  }
)

任何解决此问题的指针将不胜感激。

4

1 回答 1

1

您可以使用updateSelectInput(不要忘记添加sessionfunction(input, output, session)。此外,您需要详细说明checkboxInputisTRUE或时的情况FALSE

下面的代码应该可以工作:

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    checkboxInput("checkbox", label = "Choice a value", value = FALSE),
    selectInput("variable", "Variable:",
                c("Cylinders" = "cyl",
                  "Transmission" = "am",
                  "Gears" = "gear"),
                selected = "gear")
  ),
  server = function(input, output, session) {
    observe({
      if(input$checkbox == "TRUE"){
        toggleState(id = "variable")
      }

      else if(input$checkbox == "FALSE"){
        toggleState(id = "variable")
        updateSelectInput(session = session,
                          inputId = "variable",
                          choices = c("Cylinders" = "cyl",
                                      "Transmission" = "am",
                                      "Gears" = "gear"),
                          selected = "cyl")
      }

    })
  }
)
于 2020-03-21T10:02:57.703 回答