I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code:
const choices = new Choices('select',
{
loadingText: 'Loading...',
searchEnabled: false,
itemSelectText: '',
removeItemButton: true,
});
The dynamic select field ceases to work and the data doesn't get populated from the ajax script. The information is supposed to be fetched dynamically from the DB for the first select - course field. When I remove the above choices parameters, everything functions properly. But when I include it, the functionality breaks and the remote ajax data fails to populate.
Any suggestions on how to enable ajax data from the DB to show up in Choices.js?
I noticed there's an option to add choices using setchoices: https://github.com/jshjohnson/Choices#setchoiceschoices-value-label-replacechoices
I am unsure of how to implement those in my code. Any assistance would be greatly appreciated!
Here's the HTML snippet:
<div class="input-field">
<div class="input-select">
<select name="course_id" id="course_id" class="form-control input-lg dynamic" data-dependent="branch_id">
<option value="">Select Course</option>
@foreach($papers as $paper)
<option value="{{ $paper->course_id}}">{{ $paper->course_name }}</option>
@endforeach
</select>
</div>
</div>
<br>
<div class="input-field">
<div class="input-select">
<select name="branch_id" id="branch_id" class="form-control input-lg dynamic" data-dependent="sem_id">
<option value="">Select Branch</option>
</select>
</div>
</div>
<br>
<div class="input-field">
<div class="input-select">
<select name="sem_id" id="sem_id" class="form-control input-lg">
<option value="">Select Semester</option>
</select>
</div>
</div>
And here's the Ajax portion:
<script type="text/javascript">
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
}
});
$('#course').change(function(){
$('#branch').val('');
$('#sem').val('');
});
$('#branch').change(function(){
$('#sem').val('');
});
});
</script>