Search code examples
jqueryhtmlinputcurrency

Set value to currency in text input field


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?


Solution

  • 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,") ); 
     })
    }