I create a dynamic adding element form textfield input with livewire 3. Inside this form I have a datepicker
field and want to re-init every datepicker field when new element added on that form.
Everythings OK, but when I use wire:navigate
to pages navigate, I found an issue. My hook element.init
always error when I access this page from another page. When first navigate page visit it ok, but senconds visit error show
Uncaught TypeError: window.Livewire.find(...) is undefined
My view code
@push('script')
@script
<script>
function goBack(e) {
window.history.back();
}
Livewire.hook('element.init', ({ component, el }) => {
console.log("element.init");
if (document.querySelectorAll('[id^="date_"]').length) {
initializeDatepickers();
}
});
function initializeDatepickers() {
// Check if rows exist in the Livewire component
const rows = @this.get('rows');
if (!rows || !Array.isArray(rows)) {
return;
}
// Iterate through each row and initialize datepicker
rows.forEach((row, index) => {
const datepickerId = `#date_${index}`;
const $datepickerElement = $(datepickerId);
// Ensure the datepicker element exists before initializing
if ($datepickerElement.length) {
// Destroy existing datepicker to avoid conflicts
if ($datepickerElement.data('datepicker')) {
$datepickerElement.datepicker('destroy');
}
$datepickerElement.datepicker({
todayHighlight: true,
orientation: "bottom left",
autoclose: true,
format: "dd-mm-yyyy"
}).on("changeDate", function (e) {
@this.set(`rows.${index}.date`, e.format());
});
}
});
}
$('#tanggal_ajuan').datepicker({
todayHighlight: true,
orientation: "bottom left",
autoclose: true,
format: "dd-mm-yyyy"
}).on("changeDate", function (e) {
@this.set('tanggal_ajuan', e.format());
});
</script>
@endscript
@endpush
Now I decide to not use wire:navigate
but how to fix this issue? But I still prefer to use wire:navigate
. How to fix this issue?