Created
October 26, 2012 16:50
-
-
Save cam-gists/3959865 to your computer and use it in GitHub Desktop.
JS: Add hyphens as you type
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
function mask(str, textbox, loc, delim) { | |
var locs = loc.split(','); | |
for (var i = 0; i <= locs.length; i++) { | |
for (var k = 0; k <= str.length; k++) { | |
if (k == locs[i]) { | |
if (str.substring(k, k + 1) != delim) { | |
str = str.substring(0, k) + delim + str.substring(k, str.length) | |
} | |
} | |
} | |
} | |
textbox.value = str | |
} | |
$('#key').on({ | |
keyup: function(){ | |
cachedThis = $(this); | |
cachedThis.val(cachedThis.val().replace(/[^0-9]/g, '')); | |
return mask(this.value,this,'3,7','-'); | |
}, | |
blur: function(){ | |
return mask(this.value,this,'3,7','-'); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment