I created a form that formats phone numbers, allows only allowable keys to be pressed, and converts a lettered entry into its corresponding phone keypad number. Is there some cleanup or better coding that can be done? There is no business need for international phone numbers as it is a local business.
function pageLoad() {
$(".PhoneSelection").keypress(function (e) {
// Only allow number entry
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
// If not a number, is it a letter?
var regex2 = new RegExp("^[A-Za-z]+$");
if (regex2.test(key)) {
// Convert the letter typed to the number on the phone keypad
$(this).val($(this).val() + letterPos(key));
return false;
}
else { return false; }
}
});
$(".PhoneNum").text(function (i, text) {
// returns (999) 555-1234 from 9995551234
return text.replace(/(\d{3})?(\d{3})(\d{4})$/,
function ($0, $1, $2, $3) {
var formatted = ""; if ($1) { formatted += "(" + $1 + ") "; } if ($2) { formatted += $2 + "-"; } if ($3) { formatted += $3; } return formatted;
}
);
});
}
function letterPos(val) {
var alphaMap = { 'ABC': '2', 'DEF': '3', 'GHI': '4', 'JKL': '5', 'MNO': '6', 'PQRS': '7', 'TUV': '8', 'WXYZ': '9' };
var number = "";
$.each(alphaMap, function (key, value) {
if (key.toLowerCase().indexOf(val.toLowerCase()) > -1)
{ number = value; }
});
return number;
}
Here is how it is consumed in the view form:
<div class='PhoneNum'>9995551234</div>
<input id="ContactPhone" class="PhoneSelection nextField" type="text" placeholder="Phone" value="9995551234"></input>
Results on display:
(999) 555-1234
<input type="tel" ...>
for phone numbers.) \$\endgroup\$1-800-CALL-SAUL
and the input field comes up with180022558285
. In terms of visual feedback, this is completely useless. You're not only displaying different characters from what was typed in, but the number of characters is also different. And on top of that, your chance of detecting the typo in the ninth digit is almost zero. I'm sorry, but this whole idea is just ghastly. You would be better off sorting out your issues with iPads than going down this route. \$\endgroup\$