Skip to content

Instantly share code, notes, and snippets.

@townivan
Created June 24, 2014 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save townivan/d6dc47b4f2ffd20346b1 to your computer and use it in GitHub Desktop.
Save townivan/d6dc47b4f2ffd20346b1 to your computer and use it in GitHub Desktop.
Phone number input help with JavaScript. This adds the 1 (country code) and strips out the dash if one is entered. The type=tel makes these input boxes trigger the numberpad on the phone rather than the full keyboard.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>phoneJS</title>
<meta name="viewport" content="width=device-width">
<script>
function phoneinput (event){
var p1 = document.getElementById("p1").value;
var p2 = document.getElementById("p2").value;
p1 = p1.replace(/[^\/\d]/g,''); // get rid of non-numbers
p2 = p2.replace(/[^\/\d]/g,''); // get rid of non-numbers
var pc = "1" + p1 + p2;
document.getElementById("p1").value = p1;
document.getElementById("p2").value = p2;
document.getElementById("phonecombo").value = pc;
}
</script>
</head>
<body>
( <input id="p1" type="tel" onKeyPress="phoneinput(event);" onkeyup="phoneinput(event);" style="width:30px;" maxlength="3"> ) <input id="p2" type="tel" onKeyPress="phoneinput(event);" onkeyup="phoneinput(event);" maxlength="7">
<br><br>
<input id="phonecombo">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment