John Smith
John Smith

Reputation: 423

Coloring the checkboxGroupInput choices

In my Shiny UI I have

ui <- checkboxGroupInput("my_cbgi", "Choose Something", c("A", "B", "C", "D"))

And I would like it so that the choices (the text) A and B are colored red, but C and D are not. I tried HTML but then in the UI weird boxes like "attribs" and "children" showed up.

Thanks in advance

Upvotes: 1

Views: 1315

Answers (2)

JRMGarcia
JRMGarcia

Reputation: 303

Great Victorp, I improved your answer adding a varying behaviour to it.

library("shiny")

my.options <- c('A', 'B', 'C')
my.colors <- c('red', 'green', 'blue')

my.fun <- function() {
  res <- list()
  for (o in my.options) {
    res[[length(res)+1]] <- tags$span(o, 
                                      style = paste0('color: ', my.colors[which(my.options == o)],';'))
  }
  res
}

ui <- fluidPage(
  checkboxGroupInput(inputId = "myId", label = "Options", 
                     choiceNames = my.fun(),
                     choiceValues = my.colors
  )
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

Upvotes: 1

Victorp
Victorp

Reputation: 13856

Since shiny_1.0.1, checkboxGroupInput have a choiceNames and choiceValues arguments for passing arbitrary UI to display to the user, check this example :

library("shiny")

ui <- fluidPage(
  checkboxGroupInput(
    inputId = "my_cbgi",
    label = "Choose Something", 
    choiceNames = list(
      tags$span("A", style = "color: red;"),
      tags$span("B", style = "color: red;"), 
      tags$span("C", style = "color: blue;"), 
      tags$span("D", style = "font-weight: bold;")
    ),
    choiceValues = c("A", "B", "C", "D")
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)

Upvotes: 5

Related Questions