I have a dropdown division list when select division dynamically district loaded based on division .when select district, thana loaded dynamically.but problem is dynamic dropdown is select2 search not work
Here is my code that i have tried but search functionality not working.please give me a suggestion what have to modify to search dynamically dropdown value
<script>
$(document).ready(function() {
// Initialize Select2 for course dropdown
$('#division_id').select2({
placeholder: "Please Choose..",
tags: true,
allowClear: true,
width: '100%'
});
// Initialize Select2 for subject dropdown
$('#district_id').select2({
placeholder: "Please Choose..",
tags: true,
allowClear: true,
width: '100%',
minimumInputLength: 0, // Allow searching immediately without any minimum length requirement
ajax: {
url: function() {
// If division is not selected, return an empty string as URL
if (!$('#division_id').val()) {
return '';
}
return '/get-districts/' + $('#division_id').val();
},
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data, function(district) {
return {
id: district.id,
text: district.name,
};
}),
};
},
},
});
// Initialize Select2 for chapter dropdown
$('#thana_id').select2({
placeholder: "Please Choose..",
tags: true,
allowClear: true,
width: '100%',
minimumInputLength: 0, // Allow searching immediately without any minimum length requirement
ajax: {
url: function() {
// If district is not selected, return an empty string as URL
if (!$('#district_id').val()) {
return '';
}
return '/get-thanas/' + $('#district_id').val();
},
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data, function(thana) {
return {
id: thana.id,
text: thana.name,
};
}),
};
},
},
});
// Handle district dropdown open event
$('#district_id').on('select2:open', function() {
$('#district_id').select2('open');
$('.select2-search__field').focus(); // Focus on search input
});
// Handle thana dropdown open event
$('#thana_id').on('select2:open', function() {
$('#thana_id').select2('open');
$('.select2-search__field').focus(); // Focus on search input
});
// Handle division change event
$('#division_id').on('change', function() {
$('#district_id').val(null).trigger('change');
$('#thana_id').val(null).trigger('change');
});
// Handle district change event
$('#district_id').on('change', function() {
$('#thana_id').val(null).trigger('change');
});
});
</script>
New contributor
KM Sohel Rana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.