Question

I am encountering a problem assigning classes and hidding and showing td's. Here is my HTML:

<table id="fundTable">
    <tr> 
         <td class="rentability"> <span class="someClass"> 0.12 </span> </td>
         <td class="absoluteResult">0.66</td>
    </tr>
    <tr> 
         <td class="rentability"> <span class="someClass"> -0.24  </span> </td>
         <td class="absoluteResult">-.45</td>
    </tr>
</table>

Here is my Javascript (onchange):

$('#fundTable tr').each(function() {
    formatedAbsoluteResult = 'SOME NUMBER'
    $(this).find('td[class=absoluteResult]').fadeOut(100).html(formatedAbsoluteResult).fadeIn(100)
    if (formatedAbsoluteResult < 0)
        $(this).find('td[class=absoluteResult]').removeClass('green').addClass('red')
    else 
        $(this).find('td[class=absoluteResult]').removeClass('red').addClass('green')
}

The idea is to display the number in green if it is positive, by assigning the appropriate class. In red otherwise. This code works perfectly when I run it once on page load. Then, the td's that have an assigned class (either red or green) are not updated anymore (onchange), whereas the others are on:

$(this).find('td[class=absoluteResult]').fadeOut(100).html(formatedAbsoluteResult).fadeIn(100)

I do not understand this behaviour. Any help greatly appreciated.

Was it helpful?

Solution

I think a slight adjustment of your overall design of this block will help.

This seems to do what you are trying to accomplish (live demo at jsFiddle). Don't forget to change the parts where I improvised:

    $("#testing").keyup(function() {
    $("#fundTable tr").each(function() {
       formattedAbsoluteResult = 
        $(this).find("td.absoluteResult").fadeOut(100, function () {
            if (formattedAbsoluteResult < 0)
            {
                $("#fundTable tr").find("td.absoluteResult").removeClass("green").addClass("red");
            }
            else
            {
                $("#fundTable tr").find("td.absoluteResult").removeClass("red").addClass("green");
            }
        }).html(formattedAbsoluteResult).fadeIn(100);
    });
});

Notice the callback function used, also "keyup" instead of "onchange", but you can use whatever you need. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top