1

How can I have the value show as currency with a dollar sign and commas?

<input type="text" value="4435800" id="cost">

Returns the value in text as 4435800 but I would like it to show $4,435,800

In another thread I found the following function that applies to text but I'm not able to get it to work for values:

$.fn.digits = function(){ 
 return this.each(function(){ 
    $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
 })
}

Any suggestions?

user3330820
  • 501
  • 2
  • 7
  • 17
  • the regex [works](https://regex101.com/r/DUGBnC/1/), should you be using `.val()` or something instead of `.text()` ? – Scott Weaver Apr 25 '18 at 14:02
  • Possible duplicate of [Get the value in an input text box](https://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box) – Scott Weaver Apr 25 '18 at 14:02

1 Answers1

2

You should change "text" for "val" in order to change the value of the html element.

$.fn.digits = function(){ 
 return this.each(function(){ 
    $(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
 })
}
AlbertoCh
  • 120
  • 2
  • 6
  • I updated my OP to show what happens when I update it to "val". It doesn't actually change the value just places the newly formatted number in between the input field. Nvm missed the 2nd .val(). Thanks! – user3330820 Apr 25 '18 at 14:09