Question

I have a table that sum Columns and Rows, and shows the result of the sum. I have to change the color of each total. If is even, put it "green". If it is odd put it "red"

This is my table:

<table id="sum_table">
    <tr>
        <td><input value="0" class="sum1" /></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>
    <tr>
        <td><input value="0" class="sum1"/></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>
    <tr>
        <td><input value="0" class="sum1"/></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>

    <tr class ="totalCol">
        <td>0</td>
        <td>0</td>
        <td>0</td>
    </tr>

</table>
<button id="tabla">+</button>

JQuery:

//Sumamos las columnas
    $(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
    var $table = $(this).closest('table');
    var total = 0;
    var thisNumber = $(this).attr('class').match(/(\d+)/)[1];

    $table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
        total += parseInt(this.value);
    });

    $table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});


    //Añadimos filas y coumnas cuando se clica al boton "+".
    $("#tabla").click(function () {
        $("#sum_table tr:last-child").before("<tr>"+$("#sum_table tr:eq(0)").html()+"</tr>");
      $("tr:not(:last-child)").each(function () {
          var classname = $(this).find("td:last-child").index() + 1;
          $(this).find("td:last-child").before('<td><input class="sum' + classname + '" type="text" value="0"></td>');
      });
        $("#sum_table tr:last-child").append("<td>0</td>");
    });

//Creamos la funcion newSum para hacer la suma y mostrarlo en el total.
$(document).on('keyup','input',newSum);
function newSum() {
    var sum = 0;
    var thisRow = $(this).closest('tr');
    var total = 0;

    $(thisRow).find("td:not(.total) input").each(function () {
        sum += parseInt(this.value);
    });
    $(thisRow).find(".total").html(sum);
    $('.total').each(function () {
        total += parseInt($(this).html());
    });
}

DEMO JSFIDDLE

Était-ce utile?

La solution

Try this, put this code below in newSum() function

 if ((this.value % 2 == 0)) {
     $(this).css('color', 'green');
 } else {
     $(this).css('color', 'red');
 }

DEMO

Autres conseils

I have updated your fiddle please check.

$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
  var $table = $(this).closest('table');
  var total = 0;
  var thisNumber = $(this).attr('class').match(/(\d+)/)[1];

  $table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
    total += parseInt(this.value);
  });
  var total_field = $table.find('.totalCol td:nth-child('+thisNumber+')'); 
  total_field.html(total);
  if(total % 2 == true) {
    total_field.css("background","red");
  } 
  else {
     total_field.css("background","green");
  }
});

try this way

JQUERY CODE:

   if (total % 2 == 0)
      $table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'green'); //set green to even total
   else 
      $table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'red'); //set red to odd total

LIVE DEMO: http://jsfiddle.net/hdhZZ/7/

Happy Coding :)

Each time one of the inputs is changed, check to see if the total value is an odd or even number... This is rough, I would toggle a class rather than edit the inline css..

$('td input').on('change', function(){
    $('.totalCol td').each(function(){        
        var $total = parseInt($(this).html());
        if ($total !==0 && $total % 2 === 0) {
            $(this).css('background-color','green');
        }
        else {
            $(this).css('background-color','#fff');
        }
    });
});

I realise you've already accepted an answer, but I'd suggest rewriting your approach to the following (though the colouring approach is the same as suggested by the the other answers):

function sumTotals(){
    // caching variables:
    var table = $('#sum_table'),
        inputRows = table.find('tr:not(.totalCol)'),
        inputCells = inputRows.find('td:not(.total)');

    // iterating over each of the 'td' elements in the '.totalCol' row:
    $('.totalCol td').each(function(i,e){

        /* i is the index of the current element over which we're iterating
           among the collection returned by the selector,
           e is the element (the 'this'), which we're not using here.

           We're using ':nth-child()' to look at the 'input' elements from
           each column, and creating an array of the values using 'map()'
           and 'get()': */
        var sum = inputRows.find('td:nth-child(' + (i + 1) + ') input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
        /* 'reduce()' allows us to perform a calculation (summation) of the 
            values in the returned array: */
            return prev + curr;
        });

        // setting the text of the current 'td' to the sum,
        // using CSS to set the color to either green (even) or red (odd):
        $(this).text(sum).css('color', sum % 2 === 0 ? 'green' : 'red');
    });

    /* iterating over each of the rows with inputs, finding the
       last 'td', and updating its text: */
    inputRows.find('td:last-child').text(function(){
        // caching:
        var $this = $(this),
            /* getting all the previous 'td' elements, and their 'input'
               descendant elements, mapping their values: */
            sum = $this.prevAll('td').find('input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
            return prev + curr;
        });

        // setting the color (as above):
        $this.css('color', sum % 2 === 0 ? 'green' : 'red');
        return sum;
    });
}

$('#sum_table').on('keyup change input paste', 'tr:not(.totalCol) input', sumTotals);

JS Fiddle demo.

References:

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top