JS variable returning Nan

Asked

Viewed 1,253 times

4

I’m assigning the sum of a column in an HTML table to a JS (sum) variable, but when I print it on the screen I get an Nan, someone knows why?

<tr>
  <td style="background:#c4ffd6;" align="center" class="qtd_recuperado">
        <?php echo "$recuperado_total"; ?>
  </td>
</tr>

Then, in JS, I add up:

<script type="text/javascript">
     function sumQuantity() {

       var elements = document.getElementsByClassName('qtd_recuperado');
       var sum = 0;



       for (i=0;i< elements.length;i++) {
         sum = sum + parseFloat(elements[i].innerHTML);
       };

      document.getElementById('resultado').innerHTML = sum;
      }

       sumQuantity();
  </script>

So I try to print, like this:

<td style="background:#c4ffd6;" align="center" class="qtd_recuperado" id="resultado"></td>
  • 2

    Can you put here the HTML that reaches the browser? (after PHP). And by the way, if you generate it in PHP and it’s static HTML because you don’t add it up in PHP either?

  • I managed to make the sum using JS, the problem is time to show, so I did not do in PHP.

  • Okay, so the sum works as you want but insert inside #resultado no?

  • Related: https://answall.com/a/211239/57801

3 answers

3


Like the Sergio commented, whether his HTML is static so the best solution is to make the sum by PHP.

Now see that the problem in your solution with javascript occurs due to the contents of your column, understand the function parseFloat:

parseFloat parses a string argument, and returns a number of floating point. If it finds a character other than a signal (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to this point and ignores this character and all following characters. Right and left spaces are allowed.

If the first character cannot be converted to a number, parseFloat returns Nan

See the example below, I added a IF to avoid error.

function sumQuantity() {
  var elements= document.getElementsByClassName("qtd_recuperado");
  var sum = 0;
  var conteudo;
   
   for (i=0;i< elements.length;i++) {
     conteudo = elements[i].innerHTML;
     if(!isNaN(conteudo))
      sum += parseFloat(conteudo);
   };

document.getElementById('resultado').innerHTML = sum;
}

sumQuantity();
<table>
  <tr>
    <td style="background:#c4ffd6;" align="center" class="qtd_recuperado">
         112
    </td>
  </tr>
  <tr>
    <td style="background:#c4ffd6;" align="center" class="qtd_recuperado">
        10aa
    </td>
  </tr>
</table>
<div>
  <!-- conteudo: 11       -> retorna soma -->
  <!-- conteudo: 11Texto  -> retorna soma -->
  <!-- conteudo: Texto1   -> retorna NaN  -->
  <!-- conteudo: VAZIO    -> retorna NaN  -->
  Resultado: <span id="resultado"></span>
</div>

  • Thanks Caique, even with this code the value continues to come out as Nan, but I was able to resolve returning a position in my length. Turns out the JS was adding up the contents of the <td> that was blank, so Nan. But thanks anyway.

  • It turns out that the variable you created (content), is also getting a blank value, so continues Nan.

  • It was intentional I put only as an example for you to understand why to display Nan, analyzing your answer you could avoid this last column or any other with an if, see my new answer.

0

To detect the occurrence of an Nan (Not a number) you must use the function Number.isNaN passing the value.

var nan = 0 / 0;
var eNaN = Number.isNaN(nan); // eNaN vai ser true, pois zero sobre zero não é um número

var numero = parseInt("xpto");
if (Number.isNaN(numero))
    numero = 0; // zerando caso seja NaN

0

Thanks guys, I was able to resolve returning a position in length, since the JS was adding up the content of the last td that was blank. The correct code looked like this:

<script type="text/javascript">
     function sumQuantity() {

       var elements = document.getElementsByClassName('qtd_recuperado');
       var sum = 0;



       for (i=0;i< (elements.length)-1;i++) {
         sum = sum + parseFloat(elements[i].innerHTML);

       };
          document.getElementById('resultado').innerHTML=sum;
     }

       sumQuantity();
  </script>
  • Instead of doing this, you can check if the value is blank with if. Another thing is that you can write sum += sum instead of sum = sum +.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.