简体   繁体   中英

Adding a Condition to Javascript in the Context of R Shiny DT Datatable

I would like to make a javascript function that modifies the data of a cell ONLY if a particular condition is met. This is in the context of a datatable in R Shiny. The goal is to improve on this tremendous answer by Stephane Laurent .

What I don't understand is why adding

  if($cell.data.length > 10){...}

doesn't work. In the MWE I've set the condition to > 1 - and the code works on all cells. If you set it to > 2, it does not work on any cells.

library(DT)
library(shinipsum)

text_df <- data.frame(
  numbers = 1:3,
  letters = LETTERS[1:3],
  text    = c(
    "Lorem", 
    substr(shinipsum::lorem, 1, 100), 
    substr(shinipsum::lorem, 1, 5000)
  )
)

js <- "
function(cell) {
  var $cell = $(cell);
  $cell.contents().wrapAll('<div class=\\\"content\\\"></div>');
  var $content = $cell.find('.content');
  if($cell.data.length > 1){
  $cell.append($('<button>Read more</button>'));
  $btn = $cell.find('button');
  $content.css({
    height: '20px',
    overflow: 'hidden'
  });
  $cell.data('isLess', true);
  $btn.click(function () {
    var isLess = $cell.data('isLess');
    $content.css('height', isLess ? 'auto' : '100px');
    $(this).text(isLess ? 'Read less' : 'Read more');
    $cell.data('isLess', !isLess);
  });
  } 
}
"
datatable(
  text_df,
  rownames = FALSE,
  options = list(
    "columnDefs" = list(
      list(
        "targets" = 2,
        "createdCell" = JS(js)
      )
    )
  )
)

I edited the other post to answer but I can develop here.

The createdCell option actually is a function with five arguments:

function(cell, cellData, rowData, rowIndex, colIndex) {
  ......
}

To target the cells containing more than 100 characters, you can do:

function(cell, cellData, rowData, rowIndex, colIndex) {
  if(cellData.length > 100) {
    ......
  }
}

That should be identical to cell.data().length > 100 .

To skip the first row (remembering that indexing starts at 0 in JavaScript):

function(cell, cellData, rowData, rowIndex, colIndex) {
  if(rowIndex > 0) {
    ......
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM