Search code examples
javascriptjqueryarraysfunctionstartswith

Using the startsWith function to recognize the first three digits if zip code


I am attempting to use the startsWith function to recognize the first three digits of the zip code being entered. The zip code that I am testing is 44646. When I add this it should be recognized as 446 is one of the fields in the str array. The else statement is being recognized and is reading though.

Does anyone see what I am doing wrong?

$('#salesforce_submit').change(function () {
		zipVal = $('#zip').val();
		var zipVals = [ 44030 , 44048 , 44082 , 44003 , 44093 , 44076 , 44062 , 44021 , 44046 , 44099 , 44032 , 44047 , 44010 , 44057 , 44086 , 44064 , 44024 , 44023 , 44065 , 44022 , 44072 , 44040 , 44143 , 44094 , 44139 , 44146 , 44128 , 44105 , 44122 , 44124 , 44121 , 44117 , 44108 , 44110 , 44103 , 44106 , 44118 , 44120 , 44104 , 44114 , 44127 , 44125 , 44131 , 44134 , 44129 , 44130 , 44144 , 44109 , 44115 , 44136 , 44133 , 44147 , 44141 , 44067 , 44056 , 44087 , 44195 ];
		var str = [ 442 , 443 , 444 , 445 , 446 , 447 , 437 , 438 , 439 , 457 , 434 , 435 , 436 , 164 , 165 , 163 , 161 , 160 , 162 , 150 , 151 , 152 , 156 , 153 , 154 , 585 , 716 , 142 ];
		if ( zipVal.startsWith( +str ) ) {
			contains = 'Contain in place';
      $('#show').text(contains);
		} else {
			contains = 'Contain not in place';
      $('#show').text(contains);
		}
		console.log(contains);
		if ( zipVals.includes( +zipVal ) ) {
			zipAssign = 'AB';
		} else {
			zipAssign = '';
		}
		console.log(zipAssign);
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="salesforce_submit">
<div><input id="zip" placeholder="Zip/Postal Code*" class="input block" maxlength="6" name="zip" type="text" pattern= "[0-9]{5}"></div>
<p id="show"></p>
</form>


Solution

  • +str expressions give you a NaN since you transform array to number. So, try to check this way: if (str.find(num => zipVal.startsWith(num)) !== undefined;) ...

    And the same should be done for if ( zipVals.includes( +zipVal ) ) {