I am building a classifieds website where users can input their location information, which is then displayed on a Google Maps sidebar. However, the map does not display correctly unless a valid zip code is entered. I have tried to fix this, but have been unsuccessful. The problem is that many users do not know or ignore the zip code field.
To solve this issue, I want to store zip code information in a JSON file and use this data to automatically generate the appropriate zip code in the textfield when a user selects a state from a dropdown list. For example, if a user selects "Kuala Lumpur" from the list, the zip code "57000" should be automatically entered in the textfield using the data from the JSON file.
<label>State</label>
<select name="cp_state" id="cp_state" class="dropdownlist required"><option value="">-- Select --</option><option value="Kuala Lumpur" selected="selected">Kuala Lumpur</option><option value="Labuan">Labuan</option><option value="Malacca">Malacca</option> </select>
<label>Zip/Postal Code </label>
<input name="cp_zipcode" id="cp_zipcode" type="text" class="text" placeholder="Enter zipcode" />
JSON data
[
{
"czipcode": "57000",
"cstate": "Kuala Lumpur"
},
{
"czipcode": "75000",
"cstate": "Labuan"
},
{
"czipcode": "87000",
"ctate": "malacca"
}
]
I was able to solve my question by implementinig jQuery Autocomplete and then modifying the code to update the zip code input field with the corresponding data from the JSON file whenever an autocomplete suggestion is selected.
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"/>
</head>
<body>
<div class="ui-widget">
<label for="city">City</label>
<input id="city"/><br><br>
<label for="zipcode">Zipcode</label>
<input id="zipcode" type="text"/>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
var data = [
{ "value": "Allentown","zipcode": "88459" },
{ "value": "Anchorage", "zipcode": "72815" },
{ "value": "Athens", "zipcode": "53861" },
{ "value": "Bellevue", "zipcode": "22183" },
{ "value": "Birmingham", "zipcode": "88235" }
];
$('#city').autocomplete({
source: data, // lookup suggestion from data json
delay: 500, // delay in milliseconds before displaying suggestions
minLength: 3, // minimum number of characters before displaying suggestions
select: function (event, suggestion) {
$('#zipcode').val(suggestion.item.zipcode); // update input with respective zipcode
}
});
</script>
</body>
</html>