TAGS :Viewed: 3 - Published at: a few seconds ago

[ Jquery keeps returning NaN ]

I have a function which keeps returning NaN. I've searched the forum and tried everything that I found but obviously I'm doing something wrong seeing my (probably) weird code :)

My code:

  function bakVormTotals(targetClass){
  $.getJSON('http://shop.com/cart/?format=json', function(data){
  var totaal = 0;

 $('.grandTotal').each(function(){ ////////////
 var item = $(this);               // FOUND THIS ON FORUM
 totaal+= parseInt(item.val());    ///////////
 })
 $.each(data.cart.totals, function(index, totals){
 $('<strong/>').html('€' + (+totals.grand_total).toFixed(2)).appendTo(targetClass); //  the grand total price
 });
 });
 }

The json looks like this: "totals":{"sub_total":"335.29","taxes":[{"percentage":"0.1900","amount":63.71}],"grand_total":"399.00"}} If that may help.

Any help is greatly appreciated

UPDATE 1

Ok I've found some new interesting stuff. I changed the function above to:

  function bakVormTotals(targetClass){

  $.getJSON('http://shop.com/cart/?format=json', function(data){

  $.each(data.cart, function(index, totals){
  $('<strong/>').html('€' + totals.grand_total + '').appendTo(targetClass); // the grand total price
  });
  });
  }

Now the script returns: €undefined€undefined€undefined€undefined€undefined€undefined€undefined€undefined€1197.00

Obviously I'm in the right direction since €1197.00 is the correct value. The "undefined" stuff is probably due to the html part?? Can some body help me changing the $('') part to something like "total" so I can leave the HTML part out?

Answer 1


$('.grandTotal').each(function(){
  var item = $(this);               // FOUND THIS ON FORUM
  totaal+= parseInt(item.val()); 
  ...

In this part, you loop through a set of DOM elements. Depending on these elements, they probably do not have a function val(), so item.val() is not a number but rather undefined.

Answer 2


I think lucuma is right, you need to parse to float doing parseFloat($item.val())

Answer 3


If you call parseInt() on an empty string or undefined variable, you will get a NaN error. I suspect this is what is happening.

Do the following check to avoid these situations:

if(!isNaN(parseInt(item.val())))
{
    totaal+= parseInt(item.val());
}

Also, just to make sure you're aware, using parseInt() will drop the decimal places. using parseFloat() will retain them.