Preformatted text
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
$(document).ready(function() {
// Define the country-State mapping
var countryStateMap = {
"Select Country": [],
"Country 1": ["State 1", "State 2", "State 3"],
"Country 2": ["State 4", "State 5", "State 6"],
"Country 3": ["State 7", "State 8", "State 9"]
// Add more countries and States as needed
};
// Populate the States dropdown based on the selected countries
function populateStates() {
var selectedCountries = $('#countries').val();
var StatesDropdown = $('#States');
var selectedStates = StatesDropdown.val();
StatesDropdown.empty();
for (var i = 0; i < selectedCountries.length; i++) {
var country = selectedCountries[i];
var States = countryStateMap[country];
for (var j = 0; j < States.length; j++) {
var State = States[j];
StatesDropdown.append($('<option>').val(State).text(State));
}
}
// Set the previously selected States as selected again
StatesDropdown.val(selectedStates);
// Refresh Select2 to update the options
StatesDropdown.select2();
}
// Initialize Select2 on the countries dropdown
$('#countries').select2({
placeholder: 'Select Countries',
allowClear: true
});
// Attach event handler to the countries dropdown
$('#countries').on('change', function() {
populateStates();
});
// Initialize Select2 on the States dropdown
$('#States').select2({
placeholder: 'Select States',
allowClear: true,
multiple: true
});
// Attach event handler to the form submit button
$('form').submit(function(event) {
event.preventDefault(); // Prevent form submission
var selectedStates = $('#States').val();
console.log(selectedStates); // Perform your desired action with the selected States
});
});
</script>
<h1>Country and States Selection</h1>
<form>
<label for="countries">Select Countries:</label>
<br>
<select id="countries" name="countries" multiple>
<option></option>
<option value="Country 1">Country 1</option>
<option value="Country 2">Country 2</option>
<option value="Country 3">Country 3</option>
<!-- Add more countries as needed -->
</select>
<br><br>
<label for="States">Select States:</label>
<br>
<select id="States" name="States" multiple>
<!-- Populated dynamically based on the selected countries -->
</select>
<br><br>
<input type="submit" value="Submit">
</form>