Hi guys,
I'm trying to make a simple plugin that formats a phone number. If I use the regex outside of the plugin it works fine, however inside the plugin it seems to only replace the first time. After that you can add any characters you want and it stays, completely ruining the formatting if you have to go back and add a number at the beginning or what have you.
So here's the plugin code:
(function ($) {
$.fn.Format = function (type) {
type = type.toLowerCase();
if (type == 'phone') {
return this.bind("blur.Format", function () {
var val = $(this).val().replace(/[^a-zA-Z0-9]+/,'');
var prefix = "";
if (val.length > 0) {
if (val.substring(0, 1) == "1") {
prefix = "1";
val = val.substring(1);
}
if (val.substring(0, 1) != "(") {
val = "(" + val;
}
if (val.length > 4 && val.substring(4, 5) != ")") {
val = val.substring(0, 4) + ")" + val.substring(4);
}
if (val.length > 8 && val.substring(8, 9) != "-") {
val = val.substring(0, 8) + "-" + val.substring(8);
}
if (val.length > 13 && val.substring(13, 14) != " ") {
val = val.substring(0, 13) + " " + val.substring(13);
}
}
$(this).val(prefix + val);
});
} else {
return this;
}
};
})(jQuery);
And here is it on jsfiddle so you can see what's happening for yourself. Basically you put in your phone number the first time and it put the parens around the area code and what not. But the second time, say you forgot a number in your area code. If you go back and put it in, it keeps the current ) and adds a new one.
http://jsfiddle.net/AaBxp/
Thanks for any pointers you might have.