0

I have some input values inside a form like this:

<tr>
  <td>
      <input type="text" disabled class="qty" value="1" name="quantity">
  </td>
  <td>
    <span class="euro">€</span><input type="text" disabled class="price" value="0,60">
  </td>
</tr>
<tr>
  <td>
      <input type="text" disabled class="qty" value="1" name="quantity">
  </td>
  <td>
    <span class="euro">€</span><input type="text" disabled class="price" value="0,25">
  </td>
</tr>
// below table row is empty because product is not on stock! //
<tr>
  <td></td>
  <td></td>
</tr>
//etc...

I try to sum the qty and price input values but my script keeps returning NaN as result. I think it is because when a product is not on stock the table cells are empty. Therefore returning NaN or undefined. I've read numerous threads like this but that doesn't fix my problem.

What I have is this:

function update_amounts(){
  var sum = 0.0;
  $('#inspiration .table tbody tr').each(function() {
    var qty = $(this).find('.qty').val();
    var price = $(this).find('.price').val();
    console.log(price, qty);
    var amount = (qty*price)
        sum+=amount;
  });
  $('.total').text(sum);    
}

What I already tried is this:

var qty = parseInt($(this).find('.qty').val()) || 0;
var price = parseFloat($(this).find('.price').val()) || 0;

And:

var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
qty= parseInt(qty) || 0;
price= parseFloat(price) || 0;
console.log returns

    (2) 1 0
        0 0
    (3) 1 0

Below is what console.log returns for the original code (first one is price, second qty):

0,60 1
0,90 1
undefined undefined
0,14 1
0,12 1
0,75 1

I don't know any new option to get this fixed!

Community
  • 1
  • 1
Meules
  • 1,349
  • 4
  • 24
  • 71

1 Answers1

1

You need to use the . character to start the floating point, not ,.

value="0,60" will not be treated as a number. value="0.60" will be.

%  node
> "0.60" * 5
3
> "0,60" * 5
NaN
>

When run through parseFloat, it will hit the , and stop treating the rest as a number, so you end up with 0.

> parseFloat("0.60") * 5
3
> parseFloat("0,60") * 5
0
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335