jqueryrr-markdowndt

Why is JQuery not affecting tables in RMarkdown?


I'm trying to use JQuery on HTML tables in RMarkdown. Specifically, I'm trying add row classes to certain rows of a DT::datatable using JQuery.

I've tested the jQuery code in jsFiddle and that works fine. I've also tested basic jQuery code (changing colour of headers) in RMarkdown. This also works. I've not managed to get jQuery relating to tables working on DT::datatable in RMarkdown.

The code below is from an .Rmd file.

```
# Test
```

```
{js jQuery codechunk}
// Test that jQuery works in Rmd
$('.h1').css('color', 'red')

// Updating classes does not work
$("tr:contains('Mazda')").addClass('Mazda');

// Colour styling also does not work
$("tr:contains('Mazda')").css("color", "red")
```

```
{r R codechunk}
library(DT)
  DT::datatable(mtcars)
```

I expect that when I inspect the table, the rows with "Mazda" will be coloured red and the will have the class "Mazda".

I just see the plain DataTable, and the row classes are the standard ones.


Solution

  • I've got it! See section 2.9 of the documentation, "The callback argument."

    I made the following changes and your code worked like a charm.

    Beautiful package by the way. Thanks for introducing me to it!

    ---
    title: "It works!"
    author: "trianglegirl"
    date: "May 20, 2019"
    output: html_document
    ---
    
    ```{js jQuery-codechunk}
    const trianglegirl_function = function() {
    
      // Test that jQuery works in Rmd
      $('h1').css('color', 'red');
    
      // Updating classes does not work
      $("tr:contains('Mazda')").addClass('Mazda');
    
      // Colour styling also does not work
      $("tr:contains('Mazda')").css("color", "red");
    };
    ```
    
    ```{r R-codechunk}
    library(DT)
    DT::datatable(mtcars, callback = JS('trianglegirl_function();'))
    ```