rshinyshinyjs

R shinyjs::disable not working when using choiceNames/choiceValues in updateCheckboxGroupInput


I want a choice of a checkbox group to be disabled dependent on a selected radio button. This works perfectly with shinyjs. However, if I also conditionally change the font color of that choice, it appears to be ignoring the subsequent shinyjs call. Is it not possible to combine the two?

library(shiny)

ui <-shinyUI(fluidPage(
  shinyjs::useShinyjs(),
  fluidRow(style = "padding-left: 15px;", 
           radioButtons("options1", label=NULL,inline = TRUE,
                        c("Allow both", "Don't allow B"),
                        selected = "Allow both"),
           checkboxGroupInput(inputId = "options2", label = "", inline = TRUE,
                              choices = c("A" = "a",
                                          "B" = "b")
                              )
  )
))

This works, but doesn't change the font color of the disabled checkbox choice:

server <- function(input, output, session) {
  observe(
    if( input$options1=="Don't allow B"){
      updateCheckboxGroupInput(session,
                               inputId="options2",
                               selected=input$options2[input$options2!='b'],
                               inline=TRUE)
      shinyjs::disable(selector = "#options2 input[value='b']")
    }else{
      shinyjs::enable(selector = "#options2 input[value='b']")
    }
  )
}

shinyApp(ui,server)

This changes the text color, but doesn't disable the checkbox:

server <- function(input, output, session) {
  observe(
    if( input$options1=="Don't allow B"){
      updateCheckboxGroupInput(session,
                               inputId="options2",
                              label="",
                               choiceNames = list(
                                 tags$span("A"),
                                 tags$span("B", style = "color: grey;")),
                               choiceValues = c("a", "b"),
                               selected=input$options2[input$options2!='b'],
                               inline=TRUE)
      shinyjs::disable(selector = "#options2 input[value='b']")
    }else{
      updateCheckboxGroupInput(session,
                               inputId="options2",
                               choices = c("A" = "a",
                                           "B" = "b"),
                               selected=input$options2,
                               inline=TRUE)
      shinyjs::enable(selector = "#options2 input[value='b']")
    }
  )
}

shinyApp(ui,server)

Solution

  • There's no reason that the text color turns to grey without CSS. You can use this CSS:

    library(shiny)
    
    css <- "
    input[type=checkbox].disabled + span {
      color: grey;
    }
    "
    
    ui <-shinyUI(fluidPage(
      shinyjs::useShinyjs(),
      tags$style(HTML(css)),
      ......