We help IT Professionals succeed at work.

Populate State based on AreaCode in JS.

Jon Imms
Jon Imms asked
on
High Priority
50 Views
Last Modified: 2020-02-12
Hey There,

I need a little help tweaking my script for determining a State based on a Phone Number areacode.

I have a form, which when you enter the phone number, a hidden field will be populated with the state.   The script is working if you enter the number in 111-111-1111 or 111111111 format, but if you do (111)-111-1111 or (111)111-1111 format, it displays none.  So How do i tweak this, so it will pull the state regardless of the format.  Website here - Website

form html
<div class="rounded-lp-form">
<div class="lp-form-header">
		<h1 style="text-align: center;">Schedule a demo</h1>
		<p style="text-align: center;"><span class="text-black">Already an existing customer?</span><br />
			<a href="https://buildertrend.com/company/contact-us/">Contact us here.</a>
		</p>
  </div>
  <form id="scedule-demo-lp-form" class="" action="https://go.buildertrend.com/l/464372/2020-02-04/7lw3vg" method="get">

<div>
    <input type="text" id="full_name" name="full_name" required placeholder="Full name" required/>
    <label for="full_name" class="hide-label">Full Name</label>
 </div>  
  <div>
    <input type="email" id="email" name="email" required placeholder="Email address" />
    <label for="email" class="hide-label">Email Address</label>
  </div>
  
<div>
	<input name="phone" id="phone" type="tel" placeholder="Phone number" required>
	<label for="phone" class="hide-label">Phone*</label>
</div>
  

  <input type="hidden" name="name" value="" id="combine-name">
  <input type="hidden" name="first-name" value="" id="first-name">
  <input type="hidden" name="last-name" value="" id="last-name">
  <input type="hidden" name="state" value="" id="areacode">
  <input type="hidden" name="country" value="" id="areacodeCountry">
  
  <p class="source">
	  <input type="hidden" name="source" id="tags" value="">
  </p>
 
 <div class="lp-submit-container">
 <button class="orange lp-arrow-na" type="submit">Submit</button>
 </div>
</form>
</div>
<!-- reference state asssignmentjs file -->
<script type="text/javascript" src="/wp-content/themes/plumbweb-child/_assets/_dist/stateassignmentAK.js"></script> 

Open in new window


js file
function getState(areacode) {

    // Ensure param is a string to prevent unpredictable parsing results
    if (typeof areacode !== 'string') {
        console.log('Must pass the arecode as a string.');
        return;
    }

    // Ensure we don't parse strings starting with 0 as octal values
    const thisarea = parseInt(areacode, 10);

    const areaCodes = {'AL':[205,938,251,334],'AK':[907,250],'AR':[501,479,870],'AZ':[480,602,520,928],
                       'CA':[213,310,424,619,714,415,949,916,408,669,805,510,909,760,209,626,650,951,562,707,925,661,559,530,541,831,858,323],
                       'CO':[720,719,970],'CT':[203,959], 'DC':[202],'DE':[302],'FL':[786,407,561,813,904,754,727,850,239,321,941,352,772,386,863,785],
                       'GA':[678,770,404,912,762,229,423,478],'HI':[808],'IA':[515,319,712,563,641],'ID':[208],'IL':[847,630,773,312,708,618,217,779,309,872,815],
                       'IN':[463,219,765,574,930,260],'KS':[913,785,316,620],'KY':[859,502,270,606,513],'LA':[504,318,337,985,225],'MA':[617,978,351,781,339,413],
                       'MD':[410,240],'ME':[207],'MI':[248,734,616,313,586,517,989,269,810,231,906],'MN':[612,651,952,763,507,218,320],'MO':[314,816,573,417,636,660,479],
                       'MS':[601,662,228],'MT':[406],'NC':[704,336,910,828,252,919,984,651],'ND':[701],'NE':[402,308],'NH':[603],'NJ':[732,201,551,908,609,862,973,856,203,606],
                       'NM':[505,575],'NV':[702,775,541],'NY':[718,212,917],'OH':[614,330,216,513,740,937,440,419,567],'OK':[918,405,580,304],'OR':[541],'PA':[610,717,267,814,724,412,570,240,878],
                       'RI':[401],'SC':[843,803,864],'SD':[605,701],'TN':[615,423,865,901,731,931,456],'TX':[469,281,817,512,210,430,530,956,915,254,806,361,979,409,830,940,936,432,319,325,575,214],
                       'UT':[801,435],'VA':[757,703,804,540,434,276],'VT':[802],'WA':[206,425,509,360,253,564],'WI':[608,262,715,920,414,274],'WV':[304],'WY':[307]}

    for(state in areaCodes){
        if (areaCodes[state].indexOf(thisarea)!==-1){
            return state;
        }
    }
    
    return 'none';
}

// Function to determine the country based on areacode.
function getCountry(areacodeCountry) {

    // Ensure param is a string to prevent unpredictable parsing results
    if (typeof areacodeCountry !== 'string') {
        console.log('Must pass the arecode as a string.');
        return;
    }

    // Ensure we don't parse strings starting with 0 as octal values
    const thisareaCountry = parseInt(areacodeCountry, 10);

    const areaCodesCountry = {'Canada':[204,226,236,249,250,289,306,343,365,367,403,416,418,431,437,438,450,506,514,519,548,579,581,587,604,613,639,647,705,709,778,780,782,807,819,825,867,873,902,905]}

    for(Country in areaCodesCountry){
        if (areaCodesCountry[Country].indexOf(thisareaCountry)!==-1){
            return Country;
        }
    }
    
    return 'usa';
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT

Commented:
why not just strip all non digit characters and then get three groups?

function() {
  var pe = jQuery(this);
  var pNumber = pe.replace(/[^\d]/g,'');

  if (pNumber.length < 3) {
    return;
  }

  var areaCode = pNumber.substr(0, 3);
  jQuery('#areacode').val(getState(areaCode));
}

Open in new window

Jon ImmsWeb Developer

Author

Commented:
still cannot get this to work.

I did forget to include my forms.js

jQuery(document).ready(setupForms);

function setupForms(){
	
	if(jQuery(".wp-block-forms").size() === 0) return false;
	
	jQuery('#user-category').on('change', function(){
		
		var current = jQuery(this);
		var value = current.val();
		var category = jQuery('option[value="'+value+'"]', current).attr('data-cat');
		var primaryProject = jQuery('#primary-project');
		
		primaryProject.val(jQuery("option:first", primaryProject).val());

		jQuery('option.active', primaryProject).removeClass('active');
		jQuery('option[data-cat="'+category+'"]', primaryProject).addClass('active');
		
	});
	
	if(jQuery("#combine-name").size() === 0) return false;
	
	var nameFields = jQuery('#first-name, #last-name');
	
	nameFields.on('keyup', function(){
		jQuery('#combine-name').val(jQuery('#first-name').val() + ' ' + jQuery('#last-name').val());
	});

	jQuery('#full_name').on('blur', function() {
		var result = jQuery('#full_name').val().split(' ');
	  jQuery('#first-name').val(result[0]);
	  jQuery('#last-name').val(result[1]);
	});

	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var pe = jQuery(this);
        var pNumber = pe.val();
        if (pNumber.length < 3) {
            return;
        }

        var areaCode = pNumber.substr(0, 3);
        jQuery('#areacode').val(getState(areaCode));
	});
	
	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var peCountry = jQuery(this);
        var pNumberCountry = peCountry.val();
        if (pNumberCountry.length < 3) {
            return;
        }

        var areaCodeCountry = pNumberCountry.substr(0, 3);
        jQuery('#areacodeCountry').val(getCountry(areaCodeCountry));
	});
	
	function phoneNumberStyle() {
		var pe = jQuery(this);
		var pNumber = pe.replace(/[^\d]/g,'');
	  
		if (pNumber.length < 3) {
		  return;
		}
		var areaCode = pNumber.substr(0, 3);
		jQuery('#areacode').val(getState(areaCode));
	  }
}

Open in new window

CERTIFIED EXPERT

Commented:
you did not change thar part of the code

var pNumber = pe.val();
to
var pNumber = pe.replace(/[^\d]/g,'');

that will get rid of all simbols that are not a number, so you it will work just as if user had typed only numbers, which you said worked fine
NorieAnalyst Assistant
CERTIFIED EXPERT

Commented:
Try this to extract the area code.
var areaCodeCountry =  /[0-9]{3}/.exec(pNumberCountry)[0] )

Open in new window

Jon ImmsWeb Developer

Author

Commented:
Hey @arana,

I did try your code, but entire function fails to work when i add your change.  The hidden fields do not change.
jQuery(document).ready(setupForms);

function setupForms(){
	
	if(jQuery(".wp-block-forms").size() === 0) return false;
	
	jQuery('#user-category').on('change', function(){
		
		var current = jQuery(this);
		var value = current.val();
		var category = jQuery('option[value="'+value+'"]', current).attr('data-cat');
		var primaryProject = jQuery('#primary-project');
		
		primaryProject.val(jQuery("option:first", primaryProject).val());

		jQuery('option.active', primaryProject).removeClass('active');
		jQuery('option[data-cat="'+category+'"]', primaryProject).addClass('active');
		
	});
	
	if(jQuery("#combine-name").size() === 0) return false;
	
	var nameFields = jQuery('#first-name, #last-name');
	
	nameFields.on('keyup', function(){
		jQuery('#combine-name').val(jQuery('#first-name').val() + ' ' + jQuery('#last-name').val());
	});

	jQuery('#full_name').on('blur', function() {
		var result = jQuery('#full_name').val().split(' ');
	  jQuery('#first-name').val(result[0]);
	  jQuery('#last-name').val(result[1]);
	});

	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var pe = jQuery(this);
		//var pNumber = pe.val();
		var pNumber = pe.replace(/[^\d]/g,'');
        if (pNumber.length < 3) {
            return;
        }

        var areaCode = pNumber.substr(0, 3);
        jQuery('#areacode').val(getState(areaCode));
	});
	
	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var peCountry = jQuery(this);
		//var pNumberCountry = peCountry.val();
		var pNumberCountry = peCountry.replace(/[^\d]/g,'');

        if (pNumberCountry.length < 3) {
            return;
        }

        var areaCodeCountry = pNumberCountry.substr(0, 3);
        jQuery('#areacodeCountry').val(getCountry(areaCodeCountry));
	});
}

Open in new window

Jon ImmsWeb Developer

Author

Commented:
Hey @norie,

Trying yours and it it's throwing expected ',' error
NorieAnalyst Assistant
CERTIFIED EXPERT

Commented:
Jon

Oops, the ) at the end shouldn't be there.
r areaCodeCountry =  /[0-9]{3}/.exec(pNumberCountry)[0];

Open in new window


Here's a small demonstration.
var phonenos = ['915-111-1111' ,'289111111','(314)-111-1111','(410)111-1111']

phonenos.forEach(pNumberCountry=> {

var areaCodeCountry =  /[0-9]{3}/.exec(pNumberCountry)[0];

console.log(`Phone no:${pNumberCountry} Area Code: ${areaCodeCountry} State:${getState(areaCodeCountry)}`);

})

Open in new window

Jon ImmsWeb Developer

Author

Commented:
@norie

Comes up as state "none" - country "usa"  if i enter phone number in (402) format
NorieAnalyst Assistant
CERTIFIED EXPERT

Commented:
Jon

'402' works for me with all the variations you posted.

Code:
var phonenos = ['402-111-1111' ,'402111111','(402)-111-1111','(402)111-1111']

phonenos.forEach(pNumberCountry=> {

var areaCodeCountry =  /[0-9]{3}/.exec(pNumberCountry)[0];

console.log(`Phone no:${pNumberCountry} Area Code: ${areaCodeCountry} State:${getState(areaCodeCountry)}`);

})

Open in new window


Result:
Phone no:402-111-1111 Area Code: 402 State:NE
Phone no:402111111 Area Code: 402 State:NE
Phone no:(402)-111-1111 Area Code: 402 State:NE
Phone no:(402)111-1111 Area Code: 402 State:NE

Open in new window

Jon ImmsWeb Developer

Author

Commented:
Where are you putting your line of code?

jQuery(document).ready(setupForms);

function setupForms(){
	
	if(jQuery(".wp-block-forms").size() === 0) return false;
	
	jQuery('#user-category').on('change', function(){
		
		var current = jQuery(this);
		var value = current.val();
		var category = jQuery('option[value="'+value+'"]', current).attr('data-cat');
		var primaryProject = jQuery('#primary-project');
		
		primaryProject.val(jQuery("option:first", primaryProject).val());

		jQuery('option.active', primaryProject).removeClass('active');
		jQuery('option[data-cat="'+category+'"]', primaryProject).addClass('active');
		
	});
	
	if(jQuery("#combine-name").size() === 0) return false;
	
	var nameFields = jQuery('#first-name, #last-name');
	
	nameFields.on('keyup', function(){
		jQuery('#combine-name').val(jQuery('#first-name').val() + ' ' + jQuery('#last-name').val());
	});

	jQuery('#full_name').on('blur', function() {
		var result = jQuery('#full_name').val().split(' ');
	  jQuery('#first-name').val(result[0]);
	  jQuery('#last-name').val(result[1]);
	});

	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var pe = jQuery(this);
        var pNumber = pe.val();
        if (pNumber.length < 3) {
            return;
        }
		var areaCode =  /[0-9]{3}/.exec(pNumber)[0];
        var areaCode = pNumber.substr(0, 3);
        jQuery('#areacode').val(getState(areaCode));
	});
	
	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {
        var peCountry = jQuery(this);
        var pNumberCountry = peCountry.val();
        if (pNumberCountry.length < 3) {
            return;
        }
		var areaCodeCountry =  /[0-9]{3}/.exec(pNumberCountry)[0];
        var areaCodeCountry = pNumberCountry.substr(0, 3);
        jQuery('#areacodeCountry').val(getCountry(areaCodeCountry));
	});
}

Open in new window

Analyst Assistant
CERTIFIED EXPERT
Commented:
Try replacing lines 35-57 with this.
	//Function for passing State value through hidden field, based on phone number area code.
	jQuery('#phone').on('blur', function () {

        var pNumber =  jQuery(this);.val();
    
       console.log(pNumber);

        if (pNumber.length < 3) {
            return;
        }
	var areaCode =  /[0-9]{3}/.exec(pNumber)[0];

        console.log(areaCode);

        jQuery('#areacode').val(getState(areaCode));
	});

Open in new window


If this doesn't work, or even if it does, try opening Developer Tools (F12 in Chrome) and see what's been logged to the console.
Jon ImmsWeb Developer

Author

Commented:
You got it!! Thank you :)