R code for applying conditional formatting to multiple checkbox columns in rhandsontable package

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.

Answer №1

Finally, the issue has been resolved after some investigation. I decided to keep the question here in case it might be useful for someone else facing a similar problem. The code below successfully accomplishes the task:

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];
                  }
                    if (instance.params && hcols.includes(col) && value ) {
                    
                        td.style.background = '#C3FA9A';
                    }  else if (instance.params && hcols.includes(col) && ! value) {
                        td.style.background ='#ff4d4d'
                    } else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
      }
                    }

            ") 
  })
}
shinyApp(ui, server)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

JSON - When an Object's Value Matches

Within my JSON file, I have an object that contains an array of nested objects. I am looking for a way to trigger a function based on the value of a specific object. If the value matches a certain number, I want to display only those objects within a desig ...

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

Utilizing dplyr for data cleansing

Consider this scenario: set.seed(123456) A <- 1:500 B <- sample(1:50, 500, replace = T) C <- rep(0,500) df1 <- data.frame(A,B,C) df1$C[1] <- 1 library(dplyr) Suppose we want to filter out data where the difference in values of B is more t ...

Are several UDP sockets open across various ports?

I'm trying to get the port of a receiving server using the following code snippet: var dgram = require("dgram"); var start = 27015; for(var i = start; i < (start + 100); i++) { var server = dgram.createSocket("udp4"); server.on("message ...

What is the method for adjusting the height of a CustomScrollPanel to be 100%?

I'm trying to set a CustomScrollPanel to have a height of 100%, but I'm having trouble making it work. Here's what I've attempted: public class MyScrollPanel extends Composite implements HasWidgets { private ResizeLayoutPanel resizeLa ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Retrieving the HTML ID attribute of an anchor link within a form and sending it to the backend server

I am currently working on a project that involves a form containing an anchor link tag with a dynamic ID. I am utilizing this anchor link tag to submit the form via Javascript. However, I am facing difficulty in fetching the ID of the same anchor link tag, ...

Is there an error when iterating through each table row and extracting the values in the rows?

Here is a basic table that I am attempting to iterate through in order to retrieve the value of each cell in every row where there are <td>s present. However, I encounter an error indicating that find does not exist despite having added jQuery. Any ...

Collecting and storing all <a> tags within a variable, excluding those with specific ID names

I am facing a situation where I have a variable named notincluded: var notincluded = “one,two,three” Unfortunately, I am unable to modify the format of this variable. My challenge now is how can I convert “one,two,three” into a format that can be ...

TS2688 Error: Type definition file for 'tooltip.js' not found

Why am I getting an 'undefined' error when trying to import the Tooltip class from the npm tooltip.js package in my TypeScript file? ...

How can data be typically encapsulated within Pinia stores when leveraging the composition API?

Currently, in my Vue 3 application with Pinia, I am interested in leveraging the composition API within my Pinia stores. Take a look at this example store: export const useMyStore = defineStore("my", () => { const currentState = ref(0); return ...

In JavaScript, how can we determine the structure of an object similar to the str function in R language?

One of the great features in R is the use of the str function, which allows you to examine the structure of an object. For example, you can use it to analyze the structure of a parsed json object like this (I'm using json as an illustration): txt = ...

Encountered a parsing issue while attempting to retrieve JSON data from an API in Dialogflow

I am currently working on retrieving JSON data from the iex API. Utilizing Google's Dialogflow inline editor, I encountered an error while attempting to fetch the JSON information: Error: Parse Error at Error (native) at Socket.socketOnData (_http_cl ...

Employing a form for initiating a JavaScript function

I need help running a JavaScript method with a custom text variable as a parameter. My goal is to input some text in a form and then pass that value to the method for execution. However, I'm encountering an issue where it seems like the method is rece ...

Exploring the Big O complexity of QuickSort in JavaScript

My experience with QuickSort involved testing two algorithms on LeetCode for a specific problem. Surprisingly, both algorithms worked, but one outperformed the other significantly, leaving me puzzled about the reason behind the speed difference. One of th ...

Encountering an issue: function not located within a for loop

Currently, I'm executing the code snippet below: dat1 <- returns for (j in 1:12) set(dat1, j = j, value = wind(dat1[[j]])) However, an error message is being generated: Error in wind(dat1[[j]]) : could not find function "wind" I believe the is ...

Learn the art of merging forms with React Js! [Code snippet included]

I am currently working on building a form in reactjs inspired by the JSON Format at . index.js: import React, { useState, Fragment } from 'react'; import BasicDetails from '../components/basic_details'; import EmploymentDetails from &a ...

Handling file uploads in ReactJS and managing files from the faux path C:/fakepath/file

When attempting to upload a file using a simple form that will be processed by my back-end python code, I encountered an issue where the uploaded file path shows as C:\fakepath\test.txt. After some research, I discovered that this behavior is du ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...