Need help with **Combo Drop-Down select field**

Need help with Combo Drop-Down select field.

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:

  1. First drop-down field is named ‘State’
  2. Second drop-down fields is named 'Cities.
  3. 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:

  1. There are 50+ States in the list.
  2. About 25 Cities for every state.
  3. Names and URLs for Cities should be in external file and not within JavaScript code.
  4. 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.

Verify that the event listeners are being attached after the elements are loaded.
handl errors

document.addEventListener("DOMContentLoaded", function () {
    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 => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    data.forEach(function(city) {
                        var option = document.createElement('option');
                        option.value = city.url;
                        option.textContent = city.name;
                        citySelect.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
        }
    });

    document.getElementById('city').addEventListener('change', function() {
        var url = this.value;
        if (url) {
            console.log('Redirecting to:', url); // Log to track the URL being redirected to
            window.location.href = url; // Redirect to the selected city's URL
        }
    });
});

1 Like

What happens?

I think it should work but you might have to use window.open(URL)

<select name="" id="city">
  <option disabled selected>Select an option</option>
  <option value="https://example.com">example</option>
</select>
document.getElementById("city").addEventListener("change", function () {
  if (this.value) {
    window.open(this.value);
  }
});
1 Like

Note: Sorry my knowledge in javascript is 1/10 :(…

Nothing really happens when I try to do that. Here is the URL & direct link to all files:

Test page:
trpn(.com)/test/03/3.html

Javascript file
trpn(.com)/test/03/redirect.js

California.json
trpn(.com)/test/03/California.json

Texas.json
trpn(.com)/test/03/Texas.json

P.S. Sorry had to add domain url this way, since for some reason it didn’t allow me to add full test URL. :frowning:

How would I do that?

Look in the browser console there is an error. Comments // are not valid JSON.

1 Like

Fixed… but still cities list does not seem to populate :(.

JSON does not support dangling commas. Remove the comma after the last object.

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

That did the trick…

You really are a life-saver !!!

Thank you… Thank you… Thank you…

1 Like

Happy to help.

You can use a JSON validator to check your JSON as well if you are ever in doubt.

Happy coding.

1 Like

Will surely do. Thank you again :).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.