Disable textInput based on Shiny radio button selection

Let's say I have the following brilliant application:

library(shiny)
ui <- fluidPage(
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output) {

}
shinyApp(ui=ui, server=server)

What is the easiest way to disable textInputbased on the selected radio button? I know that I just need to add ... disabled />to the tag input, but I do not know how to do this in Shiny.

I tried to create the complete tag "manually" by inserting HTML as a string, the selected radio value and the rest of the HTML using uiOutputand renderUI(based on this ), but this did not work.

textInput generates this:

<input id="text" type="text" class="form-control" value="Disable me"/>

and I need to be able to switch between the above and the following:

<input id="text" type="text" class="form-control" value="Disable me" disabled />
+4
source share
2 answers

session$sendCustomMessage ( javascript, ) Shiny.addCustomMessageHandler ( javascript).

library(shiny)
ui <- fluidPage(
  tags$head(tags$script(HTML('
      Shiny.addCustomMessageHandler("jsCode",
        function(message) {
          eval(message.code);
        }
      );
    '))),
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output, session) {
  observe({
    if(input$radios == "disabled") {
      session$sendCustomMessage(type="jsCode",
                                list(code= "$('#text').prop('disabled',true)"))
    } else {
      session$sendCustomMessage(type="jsCode",
                                list(code= "$('#text').prop('disabled',false)"))
    }
  })
}
shinyApp(ui=ui, server=server)
+2

, shinyjs - , , , disable enable, / , toggleState / . , , JavaScript:

library(shiny)
ui <- fluidPage(
  shinyjs::useShinyjs(),
  column(3,
         radioButtons("radios", "",
                      c("Enabled" = "enabled",
                        "Disabled" = "disabled"),
                      inline = TRUE)
  ),
  column(4, textInput("text", "", value = "Disable me"))
)
server <- function(input, output, session) {
  observe({
    shinyjs::toggleState("text", input$radios == "enabled")
  })
}
shinyApp(ui=ui, server=server)

, , , , shinyjs::useShinyjs(), session shinyjs::toggleState().

: shinyjs

+10

All Articles