Created
February 10, 2016 10:12
-
-
Save ZiTAL/8d06c7f3e4a2201ca19c to your computer and use it in GitHub Desktop.
javascript: input telephone
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
<input type="tel"> | |
Live example in Codepen: <a href="http://codepen.io/ZiTAL/pen/obJgPz">http://codepen.io/ZiTAL/pen/obJgPz</a> |
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
// 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