Skip to content

Instantly share code, notes, and snippets.

@Morgantheplant
Created September 27, 2015 19:34
Show Gist options
  • Save Morgantheplant/3c4d14d16a1046370423 to your computer and use it in GitHub Desktop.
Save Morgantheplant/3c4d14d16a1046370423 to your computer and use it in GitHub Desktop.
<input type="text" id="myinput" />
var input = document.getElementById('myinput'),
availIndices = [1,2,3,6,7,8,10,11,12,13],
placeholderAry = "(___) ___-____".split(""),
counter = 0,
keyPressed,
inputAry,
indexToReplace;
input.addEventListener('focus', function(){
input.placeholder = placeholderAry.join("");
input.addEventListener('keydown', function(e){
e.preventDefault();
keyPressed = e.keyCode
if(e.keyCode === 8){
if(counter > 0){
counter--;
inputAry = input.value.split("");
indexToReplace = availIndices[counter];
inputAry.splice(indexToReplace, 1, "_");
placeHolderAry = inputAry;
input.value = inputAry.join("")
input.setSelectionRange(indexToReplace,indexToReplace);
}
}
if(keyPressed > 47 && keyPressed < 58){
if(counter === 0){
placeholderAry = "(___) ___-____".split("");
}
if(counter < 10){
indexToReplace = availIndices[counter];
placeholderAry[indexToReplace] = String.fromCharCode(keyPressed);
input.value = placeholderAry.join("");
input.setSelectionRange(indexToReplace+1,indexToReplace+1);
counter++;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment