|
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
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)" />
|