Camila Vargas Restrepo
Camila Vargas Restrepo

Reputation: 409

Shiny - access individual checkbox items by id

Is there a way to access individual checkbox items in a checkboxGroupInput by id so that these can be modified individually through css?

Example:

using the following:

#id input[type="checkbox"]:checked:after {
		background-color: #FE0004;
}

I can edit all checkboxes inside a checkboxGroupInput. I now want to edit each individual checkbox within a group. Does each option have a unique id?

Upvotes: 2

Views: 810

Answers (2)

Geovany
Geovany

Reputation: 5677

You can add an ID to each checkbox using JavaScript with shinyjs.

Here is a basic example of how you can do it. If you are creating the checkboxGroupInput dynamically, make sure to execute the JavaScript after the checkboxGroupInput is created.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  checkboxGroupInput("variable", "Variables to show:", names(iris)),
  actionButton("bt1", "Add Style")
)

server <- function(input, output, session) {
  # add an ID to each checkbox
  shinyjs::runjs(HTML('
    var checkboxes = $("#variable").find(".checkbox span");
    for(var i = 0; i < checkboxes.length; i++) {
      checkboxes[i].setAttribute("id", "checkbox_" + i);
    }
  '))

  observeEvent(input$bt1, {
    # add a custom stytle to 3er checkbox ("checkbox_2")
    shinyjs::runjs('$("#checkbox_2").attr("style", "background-color: #FE0004;")')
    # you can also use shinyjs::addClass()
  })
}

shinyApp(ui, server)

Upvotes: 2

Gregor de Cillia
Gregor de Cillia

Reputation: 7665

Maybe this helps. If you type checkboxGroupInput("A", "B", letters[1:2]) in your terminal you wil get the actual html code

checkboxGroupInput("A", "B", letters[1:2])
# <div id="A" class="form-group shiny-input-checkboxgroup shiny-input-container">
#   <label class="control-label" for="A">B</label>
#   <div class="shiny-options-group">
#     <div class="checkbox">
#       <label>
#         <input type="checkbox" name="A" value="a"/>
#         <span>a</span>
#       </label>
#     </div>
#     <div class="checkbox">
#       <label>
#         <input type="checkbox" name="A" value="b"/>
#         <span>b</span>
#       </label>
#     </div>
#   </div>
# </div>

It doesn't seem there are any IDs assigned to the individual checkboxes.

Upvotes: 0

Related Questions