Forum Moderators: open

Message Too Old, No Replies

Need help with Combo Drop-Down select field.

         

Vishal

1:42 am on Nov 21, 2023 (gmt 0)

10+ Year Member



I am trying to do this (using below code), however it does not work. Any help?

I want to create a form field redirect as below:

First drop-down field is named 'State'
Second drop-down fields is named 'Cities.
Once the user selects the desired City from the 'Cities' drop-down list, user will be redirected to URL address specified for that particular city.
Note:

There are 50+ States in the list.
About 25 Cities for every state.
Names and URLs for Cities should be in external file and not within JavaScript code.
For each state should have it's own file for list of cities and corresponding URLs.


Here is the HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>State and City Redirect</title>
</head>
<body>
<form id="locationForm">
<label for="state">State:</label>
<select id="state" name="state">
<option value="">Select a State</option>
<!-- state options -->
<option value="California">California</option>
<option value="Texas">Texas</option>
<!-- ... other states ... -->
</select>

<label for="city">City:</label>
<select id="city" name="city" disabled>
<option value="">Select a City</option>
<!-- Cities will be loaded based on state selection -->
</select>
</form>

<script src="redirect.js"></script>
</body>
</html>



Here is the code for redirect.js JavaScript file

document.getElementById('state').addEventListener('change', function() {
var state = this.value;
var citySelect = document.getElementById('city');
citySelect.innerHTML = '<option value="">Select a City</option>'; // Reset city dropdown
citySelect.disabled = !state;

if (state) {
fetch(state + '.json') // Fetch the JSON file for the selected state
.then(response => response.json())
.then(data => {
data.forEach(function(city) {
var option = document.createElement('option');
option.value = city.url;
option.textContent = city.name;
citySelect.appendChild(option);
});
});
}
});

document.getElementById('city').addEventListener('change', function() {
var url = this.value;
if (url) {
window.location.href = url; // Redirect to the selected city's URL
}
});


JSON File for Each State (e.g., California.json)

[
{ "name": "Los Angeles", "url": "https://example.com/los-angeles" },
{ "name": "San Francisco", "url": "https://example.com/san-francisco" },
// ... other cities ...
]


JSON File for Each State (e.g., Texas.json)

[
{ "name": "Dallas", "url": "https://example.com/Dallas" },
{ "name": "San Antonio", "url": "https://example.com/San Antonio" },
// ... other cities ...
]


Any help would be very much appreciated.

Thank you.

Vishal

2:52 am on Nov 21, 2023 (gmt 0)

10+ Year Member



*Update*
Got it fixed..

Json file was wrong:

Corrected code below : :)

[
{ "name": "Los Angeles", "url": "https://example.com/los-angeles" },
{ "name": "San Francisco", "url": "https://example.com/san-francisco" }
]