2

I having a html table with inline edit function,when the user edit the td if the value enter by user lower than zero the td color for specific cell would change without refreshing the page.

For example: if cell =< "-1", background-color=#FF0000

there is any way to make this work in reality?

$("#table td").each( function() {
    var thisCell = $(this);
    var cellValue = parseInt(thisCell.text());        
    if (!isNaN(cellValue) && (cellValue >=0)) {
        thisCell.css("background-color","#FF0000");
    }
});
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Xavi
  • 2,552
  • 7
  • 40
  • 59

3 Answers3

3

Just iterate every cell, parse its content and set the background color:

function updateColors () {
    $("td").css("background-color", "white");
    $("td").each (function () {
       var $cCell = $(this);
       if (Number ($cCell.text()) <= -1) {
          $cCell.css("background-color", "#FF0000");
       }
    });
}

updateColors();

// http://stackoverflow.com/a/7804973/1420197    
var allCells = document.querySelectorAll("td");
for (var i = 0; i < allCells.length; ++i) {
    allCells[i].addEventListener("DOMCharacterDataModified", function () {
        console.log(this.innerText);
        updateColors();
    });
}

Demo

JSFIDDLE

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0

Give an ID to your cell, like <td id='cellID'>34</td> then do this in jquery:

var _cellValue = $("#cellID").html();
_cellValue = parseInt(_cellValue);
if (_cellValue=<-1){
  $("#cellID").css("background-color","#FF0000");
}
Maysam
  • 7,246
  • 13
  • 68
  • 106
0

Briefly tested, hope this helps:

var colors = {
    black: {
        num: 1,
        hex: '000'
    },
    red: {
        num: 2,
        hex: 'f00'
    },
    grey: {
        num: 3,
        hex: '333'
    }
};

function getColor(num) {
    var color = '#fff'; // default
    $.each(colors, function(index, obj) {
        if (parseInt(obj.num)===parseInt(num)) {
            color = '#'+obj.hex;
        }
    });
    return color;
}

$(document).on('keyup', '#mytable td', function() {
    var current = $(this).text();
    if (current.length > 0 && !isNaN(current)) {
        $(this).css('background-color', getColor(current));
    }
    else {
        // NaN, Set default color, handle errors, etc...
        $(this).css('background-color', '#fff');
    }
});
John
  • 417
  • 2
  • 6