I have a SELECT element in which I need to automatically select the appropriate option based on the first half of the zip code entered in the textbox. British postal codes are of the form AB12 3CD, where the first section consists of 1-2 letters representing the county and a number representing the area within the county. The last 3 characters are irrelevant to this question.
For most fields, it is based on the first letter (s) only, but for some parameters it is the zip code range. HTML explains best:
<select id="country_field">
<option value="">Select</option>
<option value="AB">AB (Aberdeen)</option>
<option value="AL">AL (St. Albans)</option>
<option value="B">B (Birmingham)</option>
<option value="BA">BA (Bath)</option>
...
<option value="DD1">DD 1-7 (Dundee)</option>
<option value="DD8">DD 8-11 (Dundee)</option>
...
</select>
My code below is currently selecting the correct item when the value is exactly two letters. But I need to expand it to cover single letter codes (Birmingham) and postal code ranges (Dundee). Note. I can change the parameter values if there is a solution that requires special values, eg. DD1 / DD2 instead of DD1 / DD8.
In short:
- B2 → Birmingham
- BA3 → Bath
- DD5 → first Dundee [DD1]
- DD11 → second Dundee [DD8]
Here is the Javascript I have so far ...
window.onload = function()
{
var zipInput = document.getElementById( 'zip_field' );
var ctySelect = document.getElementById( 'county_field' );
zipInput.onchange = function()
{
var zipValue = zipInput.value;
var ctyOptions = ctySelect.options;
for ( i = 0; i < ctyOptions.length; i++ )
{
if ( zipValue.substring(0,2) == ctyOptions[i].value )
ctyOptions[i].selected = true;
}
}
}
a source
to share