简体   繁体   中英

how to change the table cell color using jquery

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");
    }
});

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

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");
}

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');
    }
});

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