I want to create a dynamic dropdown, with a condition where if the initial dropdown is selected then other dropdowns will appear according to the selected conditions.
I’ve made it and it works with javascript and ajax, but it only works on the insert form, on the update form the dropdown on change has no effect at all.
here is my js code :
<script>
$(document).ready(function() {
// Function to handle dropdown logic
function handleDropdownChange(jenis) {
// Sembunyikan kedua dropdown awalnya
$('#id_asset').hide();
$('#id_repeater').hide();
if (jenis) {
$('#loadingIndicator').show();
// Reset dropdown
$('#id_asset').html('<option value="">-- Pilih Asset --</option>');
$('#id_repeater').html('<option value="">-- Pilih Repeater --</option>');
$.ajax({
url: "/api/fetch-dropdown-data",
method: 'POST',
dataType: 'json',
data: {
jenis: jenis,
_token: "{{ csrf_token() }}"
},
success: function(response) {
console.log(response);
if (jenis === 'KP') {
$('#id_asset').show();
// Mengisi dropdown asset
$.each(response.assets, function(index, val) {
$('#id_asset').append('<option value="'+val.id+'">'+val.location_eam+'</option>');
});
} else if (jenis === 'Radio') {
$('#id_repeater').show();
// Mengisi dropdown repeater
$.each(response.repeaters, function(index, val) {
$('#id_repeater').append('<option value="'+val.id+'">'+val.loc_rep+'</option>');
});
}
$('#loadingIndicator').hide();
},
error: function(result) {
console.error('Error fetching dropdown data:', result);
$('#loadingIndicator').hide();
}
});
}
}
// Event listener untuk perubahan pada dropdown "jenis"
$('#jenis').change(function(event) {
var jenis = this.value;
handleDropdownChange(jenis);
});
// Cek apakah form adalah form update dan ada nilai default pada "jenis"
var defaultJenis = $('#jenis').val();
if (defaultJenis) {
handleDropdownChange(defaultJenis);
}
});
</script>
fyi, I use modal to display the form, and my update modal id is
id="editcomplaint{{$data->id_complaint}}">