I have several problems with select2. First, The select option of select2 is not display the value from database when I click edit button to show an edit modal.
Here's the edit modal:
here's the code:
<script>
// Edit
$('body').on('click', '.edit', function (event) {
event.preventDefault();
let id = $(this).attr('id');
$.get('/admin/diklat/diklats/' id '/edit', function (data) {
$('#code').val(data.data.code);
$('#name').val(data.data.name);
$('#lesson_hour').val(data.data.lesson_hour);
$('#department_id').val(data.data.department_id);
$('#schema_code').val(data.data.schema_code);
$('#committee').html('');
for (let index = 0; index < data.committee.length; index ) {
$('#committee').append(`<option selected value="${data.committee[index]}">${data.committee[index]}</option>`)
}
$('#id').val(data.data.id);
$('#start_date').val(data.data.start_date);
$('#end_date').val(data.data.end_date);
$('#location').val(data.data.location);
$('#regency_id').val(data.data.regency_id); // this is the part that cannot show its value
$('#modal-diklat').modal('show');
})
});
</script>
<div class="row">
<div class="col">
<div class="form-group">
<label class="form-label" for="regency_id">Kabupaten</label>
<select id="regency_id" name="regency_id" class="select2 form-control">
<option value=""></option>
@foreach ($regencys as $regency)
<option value="{{$regency->id}}">{{$regency->name}}</option>
@endforeach
</select>
</div>
</div>
</div>
Second problem is the select option of select2 is missing when I click the update button.
here:
And when the update process is done (and I want to add one more data without reload the page), it's still missing like the image shown above. But, when I reload the page, it reappears like normal.
Anyone could help me with this issues, please? I've been looking for a solution but unfortunately I still can't solve it
CodePudding user response:
Solved. For the first issue, just need to define something like
$('select').select2();
And for the second issue just need to add .trigger("change");
Example:
$('#regency_id').val(data.data.regency_id).trigger('change');
Note: OP provide an answer on question section.