1

I started off by using this solution, but I can't seem to get it to work

jQuery calculate sum of values in all text fields

Here is an example of my html

<table>
  <tbody>
    <tr id="tr_affiliation_15159">
      <td class="right col_aff_amount">15.00</td>
    </tr>
    <tr id="tr_affiliation_15189">
      <td class="right col_aff_amount">15.00</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class="total"></td>
    </tr>
  </tfoot>
</table>

This is my javascript function

function removeRow(id) {
  $("#tr_affiliation_" + id).fadeOut("slow", function() {
    $("#tr_affiliation_" + id).remove();

    // recalc total
    var total = 0;

    $('.col_aff_amount').each(function() {
      // i have tried .text(), and .html() as well as .val() but it doesn't seem to make any difference
      var val = parseFloat($(this).val());
      console.log(val);
      total += val;
  });

  $("td.total").html(parseFloat(total).toFixed(2));

}

My console log just shows a long list of NaN, why can't it extract the number?

Community
  • 1
  • 1
bumperbox
  • 10,166
  • 6
  • 43
  • 66

1 Answers1

2

you should use text() for elements other than form elements like input and textarea, also as you are doing calculation, define the variable val with an integer value before calculatiing:

$(document).ready(function(){
   // ...
   var val = 0;
   val = parseInt($(this).text(), 10);
  // ...
})

DEMO

Ram
  • 143,282
  • 16
  • 168
  • 197
  • The function is triggered when a button is pressed, so it is not in doc ready. I have added console.log($(this).text()); and I get Object [td.right] printing out instead of 15.00. (any ideas why that would be) – bumperbox Jul 14 '12 at 02:16
  • @bumperbox have you checked the demo? I can see the values on the `console.log`. – Ram Jul 14 '12 at 02:22
  • I have tried the demo, and it works great thanks. But when I copy the changes to my site, I still get NaN instead of the values. I was originally just using this plugin, but that stopped working and I couldn't figure out why http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm – bumperbox Jul 14 '12 at 02:42
  • I am calling the function from an anchor, would that cause $(this) to be different cancel – bumperbox Jul 14 '12 at 02:44
  • @bumperbox you are welcome, `$(this)` within the body of each loop refers to the the selected elements, so `$(this)` within `$('td').each()` refers to `td` element and inside of `$('a').click('function(){$(this)}')` refers to anchor links. – Ram Jul 14 '12 at 02:47
  • I have just figured out what is happening. I have a plugin called jquery.template.js (not sure where I even got it) included on the page, and after removing that, everything works as per jsfiddle. Cheers – bumperbox Jul 14 '12 at 03:21