Skip to content

Instantly share code, notes, and snippets.

@ZiTAL
Created February 10, 2016 10:12
Show Gist options
  • Save ZiTAL/8d06c7f3e4a2201ca19c to your computer and use it in GitHub Desktop.
Save ZiTAL/8d06c7f3e4a2201ca19c to your computer and use it in GitHub Desktop.
javascript: input telephone
<input type="tel">
Live example in Codepen: <a href="http://codepen.io/ZiTAL/pen/obJgPz">http://codepen.io/ZiTAL/pen/obJgPz</a>
// Live example in Codepen: http://codepen.io/ZiTAL/pen/obJgPz
(function()
{
var tel = function(element)
{
var available_keys = [35, 36, 37, 39]; // home, end, left arrow, right arrow
element.onkeydown = function(e)
{
var start = this.selectionStart;
var end = this.selectionEnd;
var code = e.keyCode || e.which;
if(available_keys.indexOf(code)!==-1)
this.setSelectionRange(start, end);
else
{
var self = this;
window.setTimeout(function()
{
var a = self.value;
a = a.replace(/[^0-9\+]/, '');
self.value = a;
self.setSelectionRange(start+1, end+1);
}, 0);
}
}
};
window.onload = function()
{
var elements = document.querySelectorAll('input[type="tel"]');
for(var i in elements)
new tel(elements[i]);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment