Search code examples
jqueryhtml-tablehighlighting

Highlighting cell based on value


I have a simple webpage with a table that shows a user and number of their subscriptions.

I am using jquery/ajax to dynamically update the data from my sql server.

I am interested in adding some highlighting to the table whenever user subscription goes above a certain threshold.

For example, user subscription >= 100, then turn the cell red.

How can I go about achieving this?

EDIT:

 (function ricSubscriptions() {
    $.ajax({
        url : '/scripts/ricSubscriptions.php',
        type : 'POST',
        data : {},
        dataType:'json',
        success : function(data) {

            var output="";
            output += "<tr>";
            output += "<th>time</th>"
            output += "<th>username</th>" 
            output += "<th>rics</th>"
            output += "<th>exclusive rics</th>"

            for (var i in data) 
            {   
                output+="<tr>";
                output+="<td>" + data[i].time.date + "</td>" + "<td>" + data[i].username + "</td>" + "<td>" + data[i].rics + "</td>" + "<td>" + data[i].exclusive_rics +"</td>";
                output+="</tr>";
            }
            $('.ricSubscriptions').html(output);

            // Make the table header toggle and remember the state
            if(window.localStorage.getItem('ricSubscriptions') === 'true'){ 
                $('.ricSubscriptions th,.ricSubscriptions td').slideUp('1000'); 
            } 
            $('.ricSubscriptions caption').click(function(){
                if(window.localStorage.getItem('ricSubscriptions') === 'true'){   
                window.localStorage.setItem('ricSubscriptions', 'false');
            } else {
                window.localStorage.setItem('ricSubscriptions', 'true'); 
            } 

            $('.ricSubscriptions th,.ricSubscriptions td').slideToggle('1000'); });

        },
        error : function(request,error) {
            alert("Request: "+JSON.stringify(request));
        } ,
        dataType: "json",
        complete: setTimeout(function() {ricSubscriptions()}, 30000),           // Run this function every 30 seconds
        timeout: 8000
    })
})();

Solution

  • Change this:

    + "<td>" + data[i].exclusive_rics +"</td>";
    

    to:

    + "<td" + (data[i].exclusive_rics > 300 ? " class='highlight'" : "") + ">" + data[i].exclusive_rics +"</td>";
    

    And add this to your CSS:

    .highlight {
        background-color: red;
    }