user1848605
user1848605

Reputation: 747

jQuery .text() returns NaN, why is that?

$('span#pricetotal').text(function() {
    var val = 0;
    for (var i = 0; i < 15; i++) {
        val += parseInt($('span#itemtotal_' + i).text());
    };
    return val;
});

I have 15x <span> where I put a price with jQuery text() function. In the code above I want to count a sum of them all and put it into span#pricetotal.

What happens however is that instead of addition (20+20=40), the element shows 2020. In the code above I used parseInt - this returns NaN.

What am I doing wrong? Thank you.

Edit: HTML of the element looks like this:

<span id="itemtotal_0">16</span>

Upvotes: 3

Views: 3086

Answers (3)

inser
inser

Reputation: 1210

It works perfectly: http://jsfiddle.net/jDnVy/5/

$('span#pricetotal').text(function() {
    var val = 0;
    for (var i = 0; i < 15; i++) {        
        val +=parseInt($('span#itemtotal_' + i).text());

    };
    return val;
});

Please, check that your itemtotal spans starts with itemtotal_0, not itemtotal_1

May be it try to find span#itemtotal_0, but it does not exists. Please, double check.

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$('#pricetotal').text(function() {
    var val = 0;
    for (var i = 0; i < 14; i++) {        
        var value = $.trim($('span#itemtotal_' + i).text());
        val +=parseInt( $.isNumeric(value) ? value : 0);
    };
    return val;
});

DEMO

NOTE:

This is safe if your span contains any space or non-numeric data. In demo you will find one span has letter a.

Upvotes: 2

bipen
bipen

Reputation: 36531

use condition to check..

try this

$('span#pricetotal').text(function() {
  var val = 0;
   for (var i = 0; i < 15; i++) {
      if($('span#itemtotal_' + i).text() != ""){  // <-- check if not empty since empty gives Nan when used pareseInt
        val += parseInt($('span#itemtotal_' + i).text());

      }
   };
 return val;
});

OR

for (var i = 0; i < 15; i++) {
    val += parseInt($('span#itemtotal_' + i).text()) || 0;
 }

Upvotes: 0

Related Questions