We help IT Professionals succeed at work.

Jquey function, get State based on Areacode on a html form

Jon Imms
Jon Imms asked
on
I want to get a function on my form, which will automatically get the users's state based on the phone number entered.
- A user, will enter their phone number with area code in the phone field. from that, it use a function, to determine the State, and pass that state as a value through a hidden field in the form.

I've got a function getState(areacode) which will do this, but i'm unsure on how to put it all together.

Here's what i have so far.

Form Code
<div class="rounded-lp-form">
	<div class="lp-form-header">
		<h1 style="text-align: center;">Get started <br/> risk free.</h1>
		<p style="text-align: center;"><span class="text-black">Already an existing customer?</span>
			<a href="/company/contact-us/">Contact us here.</a>
		</p>
	</div>

<form id="testing-lp-form" class="" action="xxxxxx" method="get">

<div>
    <input type="text" id="full_name" name="full_name" required placeholder="Full Name" />
    <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="code" value="3Q3X7">
  <input type="hidden" name="autoCode" value="true">
  <input type="hidden" name="name" value="" id="combine-name">
  <input type="hidden" name="fullname" value="" id="split-name">
  <input type="hidden" name="state" value="" id="areacode">
  <input type="hidden" name="form" value="0">
  <input type="hidden" id="autoresponder" name="autoresponder" value="TIRF-submitted">
  <p class="source">
	<input type="hidden" name="source" id="tags" value="">
  </p>
 
 <div class="lp-submit-container">
 	<input type="submit" value="Next" />
 	<img src="/wp-content/uploads/2020/02/Path-17@2x.png" width="35px" height="35px" alt="submit button arrow" class="submit-arrow">
 </div>
</form>
</div>

Open in new window


stateassignment.js
function getState(arecode) {

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

    // Ensure we have exactly 3 characters to parse
    if (areacode.length !== 3) {
         console.log('Must pass a 3-digit areacode.');
         return;
    } 

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

    const state;

    // Code blocks alphabetized by state
    if (thisarea == 205 || 938 || 251 || 334) {
        state = 'AL';
        }
    else if (thisarea == 907 || 250 ) {
        state = 'AK';
        }
    else if (thiszip >= 85000 && thiszip <= 86999) {
        st = 'AZ';
        state = 'Arizona';
        }
    else if (thiszip >= 71600 && thiszip <= 72999) {
        st = 'AR';
        state = 'Arkansas';
        }
    else if (thiszip >= 90000 && thiszip <= 96699) {
        st = 'CA';
        state = 'California';
        }
    else if (thiszip >= 80000 && thiszip <= 81999) {
        st = 'CO';
        state = 'Colorado';
        }
    else if (thiszip >= 6000 && thiszip <= 6999) {
        st = 'CT';
        state = 'Connecticut';
        }
    else if (thiszip >= 19700 && thiszip <= 19999) {
        st = 'DE';
        state = 'Delaware';
        }
    else if (thiszip >= 32000 && thiszip <= 34999) {
        st = 'FL';
        state = 'Florida';
        }
    else if (thiszip >= 30000 && thiszip <= 31999) {
        st = 'GA';
        state = 'Georgia';
        }
    else if (thiszip >= 96700 && thiszip <= 96999) {
        st = 'HI';
        state = 'Hawaii';
        }
    else if (thiszip >= 83200 && thiszip <= 83999) {
        st = 'ID';
        state = 'Idaho';
        }
    else if (thiszip >= 60000 && thiszip <= 62999) {
        st = 'IL';
        state = 'Illinois';
        }
    else if (thiszip >= 46000 && thiszip <= 47999) {
        st = 'IN';
        state = 'Indiana';
        }
    else if (thiszip >= 50000 && thiszip <= 52999) {
        st = 'IA';
        state = 'Iowa';
        }
    else if (thiszip >= 66000 && thiszip <= 67999) {
        st = 'KS';
        state = 'Kansas';
        }
    else if (thiszip >= 40000 && thiszip <= 42999) {
        st = 'KY';
        state = 'Kentucky';
        }
    else if (thiszip >= 70000 && thiszip <= 71599) {
        st = 'LA';
        state = 'Louisiana';
        }
    else if (thiszip >= 3900 && thiszip <= 4999) {
        st = 'ME';
        state = 'Maine';
        }
    else if (thiszip >= 20600 && thiszip <= 21999) {
        st = 'MD';
        state = 'Maryland';
        }
    else if (thiszip >= 1000 && thiszip <= 2799) {
        st = 'MA';
        state = 'Massachusetts';
        }
    else if (thiszip >= 48000 && thiszip <= 49999) {
        st = 'MI';
        state = 'Michigan';
        }
    else if (thiszip >= 55000 && thiszip <= 56999) {
        st = 'MN';
        state = 'Minnesota';
        }
    else if (thiszip >= 38600 && thiszip <= 39999) {
        st = 'MS';
        state = 'Mississippi';
        }
    else if (thiszip >= 63000 && thiszip <= 65999) {
        st = 'MO';
        state = 'Missouri';
        }
    else if (thiszip >= 59000 && thiszip <= 59999) {
        st = 'MT';
        state = 'Montana';
        }
    else if (thiszip >= 27000 && thiszip <= 28999) {
        st = 'NC';
        state = 'North Carolina';
        }
    else if (thiszip >= 58000 && thiszip <= 58999) {
        st = 'ND';
        state = 'North Dakota';
        }
    else if (thiszip >= 68000 && thiszip <= 69999) {
        st = 'NE';
        state = 'Nebraska';
        }
    else if (thiszip >= 88900 && thiszip <= 89999) {
        st = 'NV';
        state = 'Nevada';
        }
    else if (thiszip >= 3000 && thiszip <= 3899) {
        st = 'NH';
        state = 'New Hampshire';
        }
    else if (thiszip >= 7000 && thiszip <= 8999) {
        st = 'NJ';
        state = 'New Jersey';
        }
    else if (thiszip >= 87000 && thiszip <= 88499) {
        st = 'NM';
        state = 'New Mexico';
        }
    else if (thiszip >= 10000 && thiszip <= 14999) {
        st = 'NY';
        state = 'New York';
        }
    else if (thiszip >= 43000 && thiszip <= 45999) {
        st = 'OH';
        state = 'Ohio';
        }
    else if (thiszip >= 73000 && thiszip <= 74999) {
        st = 'OK';
        state = 'Oklahoma';
        }
    else if (thiszip >= 97000 && thiszip <= 97999) {
        st = 'OR';
        state = 'Oregon';
        }
    else if (thiszip >= 15000 && thiszip <= 19699) {
        st = 'PA';
        state = 'Pennsylvania';
        }
    else if (thiszip >= 300 && thiszip <= 999) {
        st = 'PR';
        state = 'Puerto Rico';
        }
    else if (thiszip >= 2800 && thiszip <= 2999) {
        st = 'RI';
        state = 'Rhode Island';
        }
    else if (thiszip >= 29000 && thiszip <= 29999) {
        st = 'SC';
        state = 'South Carolina';
        }
    else if (thiszip >= 57000 && thiszip <= 57999) {
        st = 'SD';
        state = 'South Dakota';
        }
    else if (thiszip >= 37000 && thiszip <= 38599) {
        st = 'TN';
        state = 'Tennessee';
        }
    else if ( (thiszip >= 75000 && thiszip <= 79999) || (thiszip >= 88500 && thiszip <= 88599) ) {
        st = 'TX';
        state = 'Texas';
        }
    else if (thiszip >= 84000 && thiszip <= 84999) {
        st = 'UT';
        state = 'Utah';
        }
    else if (thiszip >= 5000 && thiszip <= 5999) {
        st = 'VT';
        state = 'Vermont';
        }
    else if (thiszip >= 22000 && thiszip <= 24699) {
        st = 'VA';
        state = 'Virgina';
        }
    else if (thiszip >= 20000 && thiszip <= 20599) {
        st = 'DC';
        state = 'Washington DC';
        }
    else if (thiszip >= 98000 && thiszip <= 99499) {
        st = 'WA';
        state = 'Washington';
        }
    else if (thiszip >= 24700 && thiszip <= 26999) {
        st = 'WV';
        state = 'West Virginia';
        }
    else if (thiszip >= 53000 && thiszip <= 54999) {
        st = 'WI';
        state = 'Wisconsin';
        }
    else if (thiszip >= 82000 && thiszip <= 83199) {
        st = 'WY';
        state = 'Wyoming';
        }
    else {
        st = 'none';
        state = 'none';
    }

    return st;
}

Open in new window

Comment
Watch Question

ste5anSenior Developer

Commented:
hmm, I'm not sure you should do this either.

You calculate this in the backend for validation. Remember to never trust client-side data, cause it can be always be spoofed.
So doing this for a hidden column makes no sense.
Bill PrewTest your restores, not your backups...
Expert of the Year 2019
Top Expert 2016

Commented:
Based on just the info in this question, I have to agree, why would you locate this logic on the client side rather than the server side?  It doesn't sound like you want / need to make the state visible on the client side interface, so it feels like a better approach would be to do the lookup / translation when the form is submitted on the server side.  It would also give you the ability to "soft code" the translation, placing the area code to state mapping in a database table, etc, for easier maintenance down the road.


»bp

@ste5an has a valid point. Also, you only cover Alabama and Alaska via area code; everything else in that list is based on zip code.

To answer your question:
Somewhere in your HTML file you need to include a reference to stateassignment.js. It needs to be within either the <head></head> or <body></body> sections.

Since jQuery is tagged I’m going to assume that you want to use it here. Put the following script after your reference to stateassignment.js

<script>
  $('#phone').on('keyup', function(){
    var pe = $(this);
    var pNumber = pe.val();
    if(pNumber.length < 3) {
      return;
    }
   
    var areaCode = pNumber.substr(0,3);

    var state = getState(areaCode);
  });
</script>

Jon ImmsWeb Developer

Author

Commented:
how does this pass to the hidden state field?

My apologies; I had assumed you knew that part. I’ve updated the script call to include it.


<script>
  $('#phone').on('keyup', function(){
    var pe = $(this);
    var pNumber = pe.val();
    if(pNumber.length < 3) {
      return;
    }
   
    var areaCode = pNumber.substr(0,3);

    $(‘#areacode’).val(getState(areaCode));
  });
</script>

Jon ImmsWeb Developer

Author

Commented:
Thanks for your help with this Kevin.   I get the following error with this

Uncaught TypeError: $ is not a function


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(/(?<=^\S+)\s/);
    jQuery('#first-name').val(result[0]);
    jQuery('#last-name').val(result[1]);
  }); //Function for passing State value through hidden field.

  $('#phone').on('keyup', function () {
    var pe = $(this);
    var pNumber = pe.val();

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

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

Open in new window

ste5anSenior Developer

Commented:
Well, look at your code, seems that you're using jQuery instead of $. Thus rewrite it. E.g.

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;
    jQuery('#first-name, #last-name').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(/(?<=^\S+)\s/);
        jQuery('#first-name').val(result[0]);
        jQuery('#last-name').val(result[1]);
    });

    jQuery('#phone').on('keyup', 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));
    });
}

Open in new window

Jon ImmsWeb Developer

Author

Commented:
awesome, It's working now,  getting the state.

one thing though -

I type in a phone number 9071234567 and the hidden state's value correctly changes from "" to "AK".

But --

If before clicking submit, i realize i have a typo, and change the number to 9381234567, the value does not change. Stays as "AK" where i would want to change to "AL".
ste5anSenior Developer

Commented:
Well, just reconsider your actual code flow and what events are involved.

You need the state in a hidden field. So that it is sent to your server.
Currently you act on blur. Instead you should populate it once in the submit event.

p.s. this would not have happened in a solution where you calculate the state in the backend..