Currently, I am working on a Shiny App that features a rhandsontable. The last two columns of this table consist of checkboxes and I want to apply conditional formatting to them. Specifically, I aim to have a green background for true checkboxes and a red background for false ones.
After reading the post titled How to change the colour of some rows with rhandsontable and checkbox?, I managed to successfully format one column using the following code:
library(shiny)
library(rhandsontable)
ui <- fluidPage(
rHandsontableOutput('table')
)
server <- function(input, output) {
df <- data.frame(alphabet = letters[1:10],
include = TRUE,
include2 = FALSE)
output$table <- rhandsontable::renderRHandsontable({
col_highlight <- 2
rhandsontable(df, height = 500) %>%
hot_col(col_highlight,
renderer = "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
var col_value = instance.getData()[row][1]
if (col_value) {
td.style.background = '#C3FA9A';
}
if (!col_value) {
td.style.background ='#ff4d4d'
}}") })}
shinyApp(ui, server)
However, my attempt to replicate this conditional formatting for multiple columns using hot_cols
has been unsuccessful. I suspect there might be an issue in the definition of col_value
, but my limited knowledge in JavaScript is hindering me from pinpointing the problem. Here is my current code:
library(shiny)
library(rhandsontable)
ui <- fluidPage(
rHandsontableOutput('table')
)
server <- function(input, output) {
df <- data.frame(alphabet = letters[1:10],
include = TRUE,
include2 = FALSE)
output$table <- rhandsontable::renderRHandsontable({
col_highlight <- 2:3
rhandsontable(df, height = 500, col_highlight=col_highlight-1) %>%
hot_cols(
renderer = "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
if (instance.params) {
hcols = instance.params.col_highlight;
hcols = hcols instanceof Array ? hcols : [hcols];
}
var col_value = instance.getData()[row][1]
if (instance.params && hcols.includes(col) && col_value ) {
td.style.background = '#C3FA9A';
}
if (instance.params && hcols.includes(col) && ! col_value) {
td.style.background ='#ff4d4d'
}}")})}
shinyApp(ui, server)
I have considered utilizing hot_col
repeatedly as an alternative solution, but I find it less than ideal. If anyone can provide guidance on how to resolve this issue using hot_cols
, I would greatly appreciate it!
Thank you in advance.