java script – mask whole number currency fields

function numberMask(e) {
var field; //field being processed
var keyChar; //the current character
var thisKey = 0; //ascii value of character

e = e || window.event;
field = e.srcElement || e.target;

// mask whole number currency fields; includes padding between commas if necessary
if ((field.id == “price”) || (field.id == “taxes”) || (field.id == “squareFeet”)) { //processing field
if (typeof e.charCode != “undefined”) {thisKey = e.charCode;} //zero if is editing key or non-printable key – non IE
else if (e.which) {thisKey = e.which;} //NN4
else {thisKey = e.keyCode; } //zero if is editing key or non-printable key in IE
keyChar = String.fromCharCode(thisKey);

var comma = “,”;
var maxLength = 6;
if (field.id != “price”) {
maxLength = 5;
}
if (thisKey && !/[0-9]/.test(keyChar)) { //only digits and comma
if (e.returnValue) e.returnValue = false;
else if (e.preventDefault) e.preventDefault();
else return false;
} else if (thisKey && (field.value.length >=3) && (field.value.length =7) && (field.value.length <=10)) {
field.value = field.value.replace(/,/gi, ”); // g = global search; i = ignore case
field.value = Left(field.value, String(field.value).length-5) + comma + Right(Left(field.value,field.value.length-2), 3) + “,” + Right(field.value, 2);
}
}

// mask only number
if (field.id == “yearBuilt”) {
if (typeof e.charCode != “undefined”) {thisKey = e.charCode;} //zero if is editing key or non-printable key – non IE
else if (e.which) {thisKey = e.which;} //NN4
else {thisKey = e.keyCode; } //zero if is editing key or non-printable key in IE
keyChar = String.fromCharCode(thisKey);
if (thisKey && !/[0-9]/.test(keyChar)) { //only digits and comma
if (e.returnValue) e.returnValue = false;
else if (e.preventDefault) e.preventDefault();
else return false;
}
}
}
document.onkeypress = numberMask;

Advertisements

~ by UTS on May 2, 2009.

One Response to “java script – mask whole number currency fields”

  1. Hi, interesting post. I have been thinking about this issue,so thanks for writing. I will certainly be coming back to your blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: