0

I tried to multiply 2 input where user need to key in the number but the output gives me NaN value. The input number btw have comma separator. I tried to implement the method from the link below and the comma separator is working. It just that when I multiply them it gives me NaN value.

Can jQuery add commas while user typing numbers?

Can anybody help me with this. Really appreciate your help.

Javascript

$('.textInput').on('change keyup', function() {

      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40) return;

      // format number
      $(this).val(function(index, value) {
        return value
        .replace(/\D/g, "")
        .replace(/(\d)(?=(\d{3})+$)/g, '$1,');
        ;
      });

      product_total_price=0;

      var product_price= Number($('#id_Product-0-price').val());
      var product_quantity= Number($('#id_Product-0-quantity').val());

      product_total_price= product_price * product_quantity;
      $('#id_Product-0-total_price').val(product_total_price);

});
jojo1711
  • 93
  • 2
  • 10

1 Answers1

2

The problem here is that you have modified your inputs to show commas, which is totally fine, BUT you didn't remove the commas before casting/converting them to Number.

A quick test of converting a Number from string "1,234" will give you a NaN result. See screenshot:

enter image description here

Solution:

  1. Remove Comma
  2. Then cast to Number
  3. Then compute product_total_price

To remove all commas, simpy use:

yourString.replace(/,/g, '')

Hope this helps!

Algef Almocera
  • 759
  • 1
  • 6
  • 9
  • Thanks! The calculation is working now but how can I add the comma separator back to the output ? – jojo1711 Jun 11 '20 at 09:08
  • 1
    You simply need to run `product_total_price.replace(/\D/g, "").replace(/(\d)(?=(\d{3})+$)/g, '$1,')` before assigning it to your output. – Algef Almocera Jun 11 '20 at 09:18