Skip to content

Instantly share code, notes, and snippets.

@softiconic
Created March 22, 2024 14:22
Show Gist options
  • Save softiconic/adc62c203ccc50a407acbcc197b804d7 to your computer and use it in GitHub Desktop.
Save softiconic/adc62c203ccc50a407acbcc197b804d7 to your computer and use it in GitHub Desktop.
To create a jQuery function that triggers a state change event when a city is selected from a dropdown menu.
<select id="stateSelect">
<option value="">Select State</option>
<option value="California">California</option>
<option value="New York">New York</option>
<!-- Add more states as needed -->
</select>
<select id="citySelect">
<option value="">Select City</option>
<!-- Add cities for each state -->
</select>
$(document).ready(function() {
// Define city options for each state
var citiesByState = {
"California": ["Los Angeles", "San Francisco", "San Diego"],
"New York": ["New York City", "Buffalo", "Rochester"]
// Add more cities as needed
};
// Function to populate city dropdown based on selected state
function populateCities(state) {
$('#citySelect').empty(); // Clear previous options
$('#citySelect').append('<option value="">Select City</option>'); // Add default option
if (state) {
$.each(citiesByState[state], function(index, city) {
$('#citySelect').append('<option value="' + city + '">' + city + '</option>');
});
}
}
// Handle state selection change
$('#stateSelect').change(function() {
var selectedState = $(this).val();
populateCities(selectedState); // Populate city dropdown based on selected state
});
// Handle city selection change
$('#citySelect').change(function() {
var selectedCity = $(this).val();
// Perform actions when city is selected (e.g., trigger event, update UI)
console.log("Selected city: " + selectedCity);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment