Web to lead: Javascript phone formatting
In a previous post, I talked about a few ways that I customize web-to-lead forms. One of the most important improvements you can make, I think, is to add Javascript functions to format phone numbers.
When you enter 10 digits into a phone number field in Salesforce, it gets formatted as (206) 555-1212. Web to lead forms don’t do this by default, so phone numbers show up in Salesforce with inconsistent formatting. This is the reason I first started fiddling with Javascript in web-to-lead forms.
Javascript lets you change data when a website user moves out of a field - you simply respond to the onblur event by calling a function such as my formatPhone function. In the web to lead form, your phone field tag will look like this:
<input id="phone" maxlength="40" name="phone" size="20" type="text"
onblur="formatPhone(this);" />
The Javascript code goes in a <script> block within the <head> section of the web page:
<script language="JavaScript" type="text/JavaScript">
<!--
//Written by Evan Callahan, NPower Seattle
function formatPhone(num) {
var re= /\D/;
var newNum=num.value;
if (newNum != "") {
while (re.test(newNum)) {
newNum = newNum.replace(re,"");
}
if (newNum.length == 7){
newNum = '(206) ' + newNum.substring(0,3) + '-' +
newNum.substring(3,7);
num.value = newNum;
}
if (newNum.length == 10){
newNum = '(' + newNum.substring(0,3) + ') ' +
newNum.substring(3,6) + '-' +
newNum.substring(6,10);
num.value = newNum;
}
}
}
//-->
</script>
My function defaults 7 digit numbers to a 206 area code - if you aren’t fortunate enough to live in Seattle, you can replace this with a different default (or skip the whole section).
