Created
March 22, 2024 14:22
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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