pertrai1
pertrai1

Reputation: 4328

jQuery & ContentEditable Attribute

I have a test case I am working on that I am trying to dynamically update a total if a contenteditable cell is changed, the total .sum cell will update the total from the row cell totals.

<table cellspacing="2">
 <tr>
  <td contenteditable="true">1</td>
  <td>2</td>
  <td>3</td>
 </tr>
</table>

Below is my jQuery

(function() {

 $( 'tr' ).each(function() {
  var sum = 0;

   $( 'td', this ).each(function() {
    var cellNum = $(this).text();
    sum += parseInt(cellNum, 10);
   });

   var total = '<td class="sum">' + sum + '</td>';

   $( this ).append(total);

 });

})();

Upvotes: 2

Views: 2745

Answers (1)

Ram
Ram

Reputation: 144739

You can listen to blur or keyup or input event. If you use append method then you will get unexpected results, i.e the result of last calculations will be added to the current result, I have assumed that you add another td to each row.

$('table').on('blur', 'td[contenteditable]', cal);

function cal() {
    $('tr').each(function () {
        var sum = 0;
        $('td:not(.total)', this).each(function () {
            var cellNum = $(this).text();
            sum += parseInt(cellNum, 10);
        });
        $('td.total', this).text(sum);
    });
}

http://jsfiddle.net/td5Hm/

Note that if you add a non-numeric value total value will be a NaN(Not a Number) value. You can use isNaN() function and improve your code.

Upvotes: 2

Related Questions