JS script to format DataGrid cells based on cell contents

Here is a script you can use to format DataGrid cells or change what they contain based on their contents. This is useful when you, for example, want to display an image instead of the text or attach a class.

Here is how to set it up:

  1. Create a DataGrid and assign data in an event or script
  2. Assign a class to the DataGrid in the DataGrid properties (I used ‘WatchedDataGrid’ in the example script below)
  3. Drag a Javascript action into the event (below the SetValue that assigns the data to the DataGrid)
  4. Assign the script below to the Javascript action. In this script are a few examples for what you could do in this script.
var DataGridClass = "WatchedDataGrid";
var ColumnToFormat ="PaymentStatus";

function formatDG(){
 $('.' + DataGridClass + ' td[data-column-name="' + ColumnToFormat + '"]').each(
function(){
  /*ADD YOUR CONDITIONS HERE*/
 /*checks if cell contents contains the letters 'Can' (case sensitive)*/
 if ($(this).text().indexOf("Can") > -1) {
 /*Adds a title attribute to the cell*/
  $(this).attr("title","Column contains 'Can'");
 }
   /*checks if cell contents is the full word 'Unpaid'*/
  if($(this).text() == "Unpaid") {
    /*Replaces the cell contents with an embedded files called close.png*/
    var img="<img src='/Content/EmbeddedFiles/close.png' style='height:20px;width:20px;'>";
    $(this).html(img);
  }
  /*uses a regular expression to check if cell does not contain a well formed email address*/
  if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(this).text())){
    /*Adds a class called 'error' to the cell*/
    $(this).addClass("error");
  }
/*CONDITIONS END*/
 });
}

formatDG();

$(window).on('DOMNodeInserted', function(e){
var targetchildren = e.target.childNodes;  
for (var i = 0; i < targetchildren.length; i++) {
 if(targetchildren[i].classList){
  if(targetchildren[i].classList.contains(DataGridClass)){
    formatDG();       
  }
 }
}
});
1 Like