下拉列表。该下拉列表用于选择一个国家,它应该以一个国家列表初始化,同时还可以预选为特定州的当前分配的国家。 第一次我打开模态,一切正常:
select2组件正确初始化。国家的负载清单。
但是它没有在Select框中显示。
save和模态关闭时,当我重新打开其他任何状态
时,select2组件都无法重新初始化。即使使用自定义JavaScript,它也不会重新初始化,也不会显示所选国家。直接使用select2在Livewire组件内使用Select2 this this不起作用,因为LiveWire会动态重新呈现模态内容。
我在这个论坛上看到了类似问题的解决方案,这些解决方案说要设置
I编写了以下代码以检测模态何时更新,但是Select2仍然无法正确重新初始化。
<select class="form-select border border-light"
data-control="select2"
data-dropdown-parent="#kt_modal_update_state"
data-placeholder="Select an option"
data-allow-clear="true"
id="select_state_update_country">
<option></option>
<?php foreach ($countries as $country) { ?>
<option value="{{ $country->id }}">{{ $country->name }} ({{ $country->code }})</option>
<?php } ?>
</select>
<script>
document.addEventListener('livewire:initialized', function() {
// Initialize on modal show
$('#kt_modal_update_state').on('shown.bs.modal', function() {
// First destroy any existing select2 instance
if ($('#select_state_update_country').data('select2')) {
$('#select_state_update_country').select2('destroy');
}
// Initialize select2
$('#select_state_update_country').select2({
placeholder: 'Select an option',
allowClear: true,
dropdownParent: '#kt_modal_update_state'
}).on('change', function() {
@this.set('country_id', $(this).val());
});
// Set the selected value after initialization
setTimeout(function() {
$('#select_state_update_country').val(@this.country_id).trigger('change');
}, 100);
});
});
// Re-initialize when Livewire updates
document.addEventListener('livewire:updated', function() {
if ($('#kt_modal_update_state').is(':visible')) {
$('#select_state_update_country').val(@this.country_id).trigger('change');
}
});
</script>
Hello@Ahmad Faizan如果您使用LiveWire 3,请尝试此尝试
<script>
Livewire.hook('morph.updated', ({ component, el }) => {
$('#select_state_update_country').select2({
width: '100%',
});
})
</script>