I am using Choices.js ( https://github.com/jshjohnson/Choices). I am also using Ajax to populate data into my select field dynamically from database. The problem I am facing is when I use following code:
const choices = new Choices('select',
{
loadingText: 'Loading...',
searchEnabled: false,
itemSelectText: '',
removeItemButton: true,
});
The dynamic select field stops working and data does not come from ajax script. Here the data comes dynamically from DB in the first select - course field. If I remove the above choices parameters, everything works fine. But As I add it, it breaks and remote ajax data does not populate.
Any idea how to enable ajax data that comes from DB to show up in Choices.js
I see there is an option to add using setchoices: https://github.com/jshjohnson/Choices#setchoiceschoices-value-label-replacechoices
I am not sure how to use those in my code. Any help will be appreciated!
Here's the html script
<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>
Here's the Ajax:
<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>