1

I am building a Shiny App where users have to complete several mandatory questions in the form of radioButtons, numericInputs, and textInputs in order to generate an output. To highlight which questions still need to be completed, I would like the label text to initially be rendered as "red", but then switch to "black" once a value has been selected and/or inputted into the widgets.

library(shiny)
ui <- fluidPage(
  sidebarPanel(
      radioButtons("my_radio_button", tags$p("Choose an Option", style = "color:red;"), choices = c("Option 1", "Option 2"), selected = character(0)),
  )
)

server <- function(input, output, session) {
  observeEvent(input$val, {
    x <- input$my_radio_button
    if (x == "Option 1" | x == "Option 2")  {

      ## MAKE "Choose an Option" LABEL TURN BLACK
    }

  })
}

shinyApp(ui, server)

I found this example on stack exchange (R shiny conditionally change numericInput background colour) where they conditionally changed the background colour of the widget, but I don't know enough about programming to modify it to change the label text instead.

Any help would be greatly appreciated. Thanks!

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22

1 Answers1

1

You can use shinyjs

  1. add shinyjs::useShinyjs() to the beginning of ui
  2. add an id to the label param of the radioButtons ui element. I've used r_label in the example below
  3. Observe for changes to input$my_radio_button, which trigger calls to shinyjs::html()

Full code below:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  sidebarPanel(
    radioButtons("my_radio_button", 
                 label=tags$p("Choose an Option", style = "color:red;", id="r_label"),
                 choices = c("Option 1", "Option 2"), selected = character(0)),
  )
)

server <- function(input, output, session) {
  observeEvent(input$my_radio_button, {
      shinyjs::html("r_label", "<p style='color:black'>Choose an Option</p>")
    })
}

shinyApp(ui, server)
langtang
  • 22,248
  • 1
  • 12
  • 27