0

I am trying to get numbers with commas using JavaScript but it's not working. Please check my code and let me know where I went wrong. Please don't mark this question as a duplicate; I know this question has been asked before, but it's not helping me. Thanks in advance. Here is what I have tried-

function numberWithCommas() {
  var x = document.getElementById('abc').value;
    x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

html code-

<input type="text"  onblur="calculate(); numberWithCommas()" name="abc" id="abc" placeholder="abc" />
Dycey
  • 4,767
  • 5
  • 47
  • 86
  • The code in the answers [here](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) can help –  Jun 11 '16 at 14:37

1 Answers1

0

I see in your code that onblur you try to initiliaze two functions: calculate() and numberWithCommas(). In your code above the function calculate() is not defined. Make sure that it is in your final code otherwise you will get a Reference Error and the code will not run as you expect.

I made a test and your code seems to work fine regarding numberWithCommas() function. Only you need to assign to the input form the new value in which you add the commas. Please have a look at the code below:

JS

function numberWithCommas() {
  var x = document.getElementById('abc').value;
  var y = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  document.getElementById('abc').value = y;
}

HTML:

<input type="text"  onblur="numberWithCommas()" name="abc" id="abc" placeholder="abc" />

You can see that I removed the calculate() function because it is not defined in the code you shown. But of course you can use it in case it exists in your final code snippet. You have a fiddle here with the working example: https://jsfiddle.net/fxduzemx/

Bogdan Lungu
  • 786
  • 1
  • 9
  • 16