Created
August 12, 2013 14:59
-
-
Save jwaltonmedia/6211581 to your computer and use it in GitHub Desktop.
This is a jQuery plugin used to create formatted phone number values. A list of approved formats can be found in the code comments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.phoneNumberFormatter = function(format) { | |
/*supported formats: | |
* '(xxx)-xxx-xxxx', | |
* 'xxx-xxxx', | |
* '(xxx)xxx-xxxx', | |
* '+x(xxx)xxx-xxxx', | |
* '+x-(xxx)-xxx-xxxx' | |
* */ | |
var element = this, | |
avoidKeyCodes = [8, 39, 37]; | |
function finalString(originalText, formattedText) { | |
if (originalText.length < 4) { | |
return originalText; | |
} else if (formattedText.indexOf('x') < 0) { | |
return formattedText; | |
} else { | |
return formattedText.slice(0, formattedText.indexOf('x')); | |
} | |
} | |
format = format.toLowerCase(); | |
element.attr('maxlength', format.length); | |
element.on('keyup', function(e) { | |
if (avoidKeyCodes.indexOf(e.keyCode) < 0) { | |
var returnedString = format.toLowerCase().split(''), | |
text = element.val().replace(/[^\d.]/g, '').split(''), | |
entry = 0; | |
for (var i = 0, j = format.length; i < j; i++) { | |
var val = format[i]; | |
if (val == 'x') { | |
returnedString[i] = text[entry]; | |
entry++ | |
if (entry == text.length) { | |
break; | |
} | |
} | |
} | |
element.val(finalString(text.join(''), returnedString.join(''))); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment