Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created October 26, 2012 16:50
Show Gist options
  • Save cam-gists/3959865 to your computer and use it in GitHub Desktop.
Save cam-gists/3959865 to your computer and use it in GitHub Desktop.
JS: Add hyphens as you type
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