Javascript - Simple function to format currency values in a textbox
 
Rating: 2 user(s) have rated this article 5.0 out of 5 stars
Posted by: chimaera, on 1/26/2010, in category "Javascript"
Views: this article has been read 421 times


Delicious Bookmark this on Delicious

This function can be added to something like the javascript onblur event and will format the value of a textbox by adding comma's to a monetary amount.  If the user entered something like '50000' then the function would set it to'50,000'. This function assumes a non-decimal value.


 function FormatCurrency(e)
 {
    var val = e.value;

    // Replace any non-digit character

    // to include decimals
    val = val.replace(/[^0-9]/g, '');

    if (val != "") {
         var length         = val.length;
         var fullLength  = val.length;

        while (length > 3){
            val = val.substring(0, length - 3)) + ',' + val.substring((length - 3), fullLength);


            length -= 3;
            fullLength++;
//to account for the comma we just added
        }

       e.value = val;
     } else

          e.value = "";
    
 }

 

 You can try it out here: Note: this will remove a decimal and convert the number to a whole number

Here's an example of using it on the onblur event of a textbox:


  < input id="txtSalary"  type="text" size="20" onblur="FormatCurrency(this)" />

 

 

 

Share and Bookmark

LinkedIn Google Del.icio.us Digg Reddit Stumble Upon

DISCLAIMER: This information is provided "as is". The author, publishers and marketers of this information disclaim any loss or liability, either directly or indirectly as a consequence of applying the information presented herein, or in regard to the use and application of said information. No guarantee is given, either expressed or implied, in regard to the merchantability, accuracy, or acceptability of the information.


How would you rate this article?

User Feedback

Post your comment
Name:
Comment:
Insert Cancel
Questions...
Have you upgraded to Windows 7?


Archived Polls