Search code examples
jquerycellbackground-colorhandsontable

Handsontable change cell color with respect to the next cell of next column


I have a handsontable as follows:

$(document).ready(function () {
$("#example1grid").handsontable({
    colHeaders: [],        
  });

  var data = [
    ["2008", 10, 11, 12, 13],
    ["2009", 20, 0, 14, 13],
    ["2010", 30,35, 12, 13]
  ];

  $("#example1grid").handsontable("loadData", data);   

});

What I need is:

My column B having values : 10,20,30 and column C -> 11,0,35

If value in cell C > value in cell B then background-color of cell B should be red else background-color of cell cell B should be green.

So in Result Cell B with values 10,30 -> RED and 20 -> Green

Check the fiddle: FIDDLE


Solution

  • Try:

    $(document).ready(function () {
    
        $("#example1grid").handsontable({
            colHeaders: ["", "Kia", "Nissan", "Toyota", "Honda"],        
          });
    
          var data = [
            ["2008", 10, 11, 12, 13],
            ["2009", 20, 11, 14, 13],
            ["2010", 30, 15, 12, 13]
          ];
    
          $("#example1grid").handsontable("loadData", data);   
            //$('td').css('background-color', 'red');
        });
        Handsontable.hooks.add('afterRender', function(){
          var f = $('.htCore').find('tbody tr td:nth-child(2)');
          var s = $('.htCore').find('tbody tr td:nth-child(3)');
             f.each(function(i,v){
             if (s.eq(i).text() > $(v).text()) {
               $(v).css({'background':'red'});
             } else {
               $(v).css({'background':'green'});
             }
             });
        });
    

    http://jsfiddle.net/2ra8gwa7/1/

    or :

      $("#example1grid").handsontable("loadData", data);   
        //$('td').css('background-color', 'red');
    });
    Handsontable.hooks.add('afterRender', function() {
    var d = this;
    var col1 = d.getDataAtCol(1);
    var col2 = d.getDataAtCol(2);
    $.each(col1,function(i,v){
    
     if (col2[i] > v ) {
      $(d.getCell(i,1)).css({'background':'red'});
     } else {
     $(d.getCell(i,1)).css({'background':'green'});
     }
    });
    

    http://jsfiddle.net/L77wjmk9/