Using a for loop within the rowCallback parameter of the datatable function in R that contains JavaScript code

Incorporating conditional formatting into a Shiny app datatable with rowCallback options poses a challenge due to the dynamic nature of table size changes. The aim is to change the background color based on whether values in certain columns meet specific conditions. One approach involves utilizing a for loop to define which columns should be formatted.

Manually specifying the columns for conditional formatting works well:

if (!require(devtools)) install.packages("devtools"); library(devtools)
if (!require(DT)) devtools::install_github("rstudio/DT"); library(DT)

trial <- matrix(c(3,4,1,2,1,2,4,2,5), ncol=3)
colnames(trial) <- c('value', 'min', 'max')
trial.table <- data.frame(trial)

DT::datatable(trial.table,options = list(rowCallback = JS('
                                                          function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                                          if (parseFloat(aData[2]) > aData[1])
                                                          $("td:eq(2)", nRow).css("background-color", "orange");
                                                          if (parseFloat(aData[2]) > aData[1])
                                                          $("td:eq(3)", nRow).css("background-color", "orange");
                                                          }')))

Attempting to apply a similar logic using a loop leads to a blank display:

DT::datatable(trial.table,options = list(rowCallback = JS('
                                                          function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                                          for (i =2, i < 4, i++) {
                                                              if (parseFloat(aData[i]) > aData[1])
                                                              $("td:eq(i)", nRow).css("background-color", "orange");
                                                              }
                                                          }')))

Is it possible to use for loops effectively within Javascript in R?

Answer №1

To properly close the for loop, you need to add a right-curly brace that is currently missing.

Answer №2

After some investigation, I have managed to identify and address two key issues in the code.

  1. A syntax error has been detected in the for loop within JavaScript due to incorrect argument separation with semicolons.
  2. The variable 'i' is enclosed in double quotes on the second line of the for loop, causing confusion for JavaScript as it cannot process variables within quotes. To resolve this, we must move 'i' outside of the double quotes to pass its current value correctly.

-

trial <- matrix(c(3,4,1,2,1,2,4,2,5), ncol=3)
colnames(trial) <- c('value', 'min', 'max')
trial.table <- data.frame(trial)

DT::datatable(trial.table,options = list(rowCallback = JS('
                                                          function(nRow, aData) {
                                                          for (i=2; i < 4; i++) {
                                                              if (parseFloat(aData[i]) > aData[1])
                                                              $("td:eq(" + i + ")", nRow).css("background-color", "orange");
                                                              }
                                                          }')))

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

Cordova iOS displaying problem when loading Google Maps

Whenever I launch Google Maps through a google map URL for the first time (if Google Maps is not already running in the background), directions do not display. However, if Google Maps is running in the background, the directions show up as expected. I am ...

Can JavaScript be used to mimic selecting a location from the autocomplete dropdown in Google Maps API 3?

Currently, I am attempting to automate the process of selecting items from the autocomplete dropdown in the Google Maps API v3 places library using jQuery. However, I am facing difficulty in identifying the necessary javascript code to select an item from ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

Utilizing dropzone.js for file uploads triggered by clicking with ASP.NET Service

Hello everyone and thank you in advance for your help. I am trying to implement a Dropzone.js Upload box on my webpage where users can drag and drop files into the box and then click a button to upload them to a folder using a backend API. However, I am fa ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

Filter the data to exclude entries with missing monthly information

Within my dataset df, I am looking to segment the data into 10-day intervals. Specifically, I want to focus on individuals within a specific year who have complete months (e.g., 01-01-2011 - 01-31-2021). How can I apply a filter to only include those wit ...

JavaScript fails to function properly on FireFox

I'm currently troubleshooting a script that works in Chrome but not in FireFox. I suspect it's due to the webkit syntax, so I tried converting it to a standard gradient without success. Can you help me identify what's causing the issue? Web ...

How do I incorporate pagination into a PL-SQL dynamic content table in Oracle Apex?

I've successfully created a PL-SQL dynamic content report in Oracle Apex, but I'm struggling with implementing pagination. With too many rows to display at once, adding pagination will greatly enhance the user experience. Here is a snippet of my ...

The function req.isAuthenticated() always returns false and never evaluates to true

My goal is to create user authentication using the following code: userRouter.post("/login", passport.authenticate("local", { session: false }), (req, res) => { if (req.isAuthenticated()) { const { _id, username } = req.user; const t ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Contrast objects and incorporate elements that are different

In my scenario, I have a list of days where employees are scheduled to work. However, on the website, I need to display the remaining days as leave. In cases where an employee has two different shifts, there can be two elements in the object. var WorkDays ...

Showcase JSON data within a designated div

As someone new to HTML, JavaScript and Vue, I'm unsure if my issue is specific to Vue or can be resolved with some JavaScript magic. I have a Node.js based service with a UI built in Vue.js. The page content is generated from a markdown editor which ...

Issue with Webpack in vue.js project when incorporating sasssass causing errors

I am new to Vue.js and webpack, and I'm not sure if the issue lies with the packages or my own mistake. Steps to replicate the problem: Create a new Vue project using the webpack template ~ vue init webpack sass-test ? Project name sass-test ? Proj ...

What is the best method for achieving a pristine white floor with subtle shadows?

I'm struggling to achieve a white floor with shadows on it, but all I end up with is a lightgray floor with very thin shadow. Here's my floor and light configuration: const ModelSceneEnvironment = () => { return ( <> {/* Lig ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

Trouble with Bootstrap Modal not closing properly in Chrome and Safari

ISSUE: I'm facing a problem where clicking on the X (font awesome icon) doesn't close the modal popup as expected. https://i.sstatic.net/yXnwA.jpg LIMITED FUNCTIONALITY ON CERTAIN BROWSERS: Currently, the X button for closing the modal works o ...

Hello, I am working on importing data from Nasdaq into R but unfortunately encountering an error

When trying to import data from the NASDAQ into R using the following code: nasdaq <- read.table(nasdaqFile, header = TRUE, sep = ",")[,c("Date","Adj.close")] I encountered this error message: Error in `[.data.frame`(read.table(nasdaqFile, header = T ...

Instructions for implementing this script in HTML and JavaScript: utilize the clone() function

I came across this code snippet here function displaytickets(){ var $panel = $('<div/>').addClass('col-xs-3 panel panel-default') $panel.append($('<div><h3 class="panel-title">Title</h3></div>&a ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

What can I do to resolve a node server issue with the error message "npm ERR! code ELIFECYCLE npm ERR! errno 1"?

npm ERROR! code ELIFECYCLE npm ERROR! errno 1 npm ERROR! [email protected] start: node server npm ERROR! Exit status 1 npm ERROR! npm ERROR! Task failed at the [email protected] start script. npm ERROR! This may not necessarily be an ...