Search code examples
javascriptjqueryajaxaddclassremoveclass

the use of addClass/removeClass of a table td with ajax


The following code outputs a table with values, and according to the value, it gets a layout. I use jQuery (Ajax) to update the information every 10 seconds.

php script that generates the wanted variables and stores (echoes) them into a json array (example.php)

$variable1 = 20;

if ($variable1 > 0) {
$td_variable1class="positive";
} else {
$td_variable1class="negative";
}

$array['variable1']      = $variable1;
$array['td_variable1']   = $td_variable1;

echo json_encode($array);

html table where the variable is retrieved from the json generated by the example.php:

<table>
    <tr>
        <td class='variable1class'>
        <div id='variable1'></div>
        </td>
    </tr>
</table>

javascript:

<script type="text/javascript">
   $(function() {
     refresh();
    });

    function refresh() {
         $.getJSON('example.php', function(data) {
            $('div#variable1').html(data.variable1);
            $('td.td_variable1').addClass(data.td_variable1);
       });
    setTimeout("refresh()",10000);
   }

The problem is the "addClass" adds a class to the existing class, resulting in an output like this:

before the refresh:

<td class="td_variable1 positive">

after (assuming the variable changed from positive to negative):

<td class="td_variable1 positive negative">

I tried to avoid this by using removeclass:

$('td.td_variable1').removeClass().addClass(data.td_variable1);

But then the actual class name of the td is removed and my output looks like this:

<td class="negative"> 

and it should look like this:

<td class="td_variable1 negative"> 

Thanks for your help in advance!


Solution

  • Assuming you only have those 2 options, remove both (and only those two) then add the new one:

    $('td.td_variable1').removeClass("positive negative").addClass(data.td_variable1);