I am trying to bind backAfterSaveStatus
value to hidden input and for some reason then form is submited backAfterSave
value is null.
After that I go back and submit form again - backAfterSave
value is 1. Where is the problem?
I tried same thing without prevent
and submit()
but it's not working still. Also I had dumped div with x-text
and code makes hidden input 1 before form submit. What I am doing wrong?
<form action="<...>" method="post">
<div x-data="{
backAfterSaveStatus: '',
backAfterSave () {
this.backAfterSaveStatus = '1';
document.querySelector('form.withBackAfterSave').submit();
}
}">
<input name="backAfterSave" :value="backAfterSaveStatus">
<div>
<span>
<button x-on:click.prevent="backAfterSave()" type="submit">
Save & back
</button>
</span>
<span>
<button type="submit">
Save
</button>
</span>
</div>
</div>
</form>
I want same result as below:
let buttonBackAfterSave = document.getElementById('button-back-after-save');
if (buttonBackAfterSave) {
buttonBackAfterSave.addEventListener('click', () => document.getElementById('input-back-after-save').value = 1);
}
The problem is the form being submitted "too fast" (the backAfterSaveStatus value isn't done binding to the input). Use $nextTick so Alpine waits until the value is properly changed.
<form method="post" class="withBackAfterSave">
@csrf
<div x-data="{
backAfterSaveStatus: '',
backAfterSave () {
this.backAfterSaveStatus = '1';
this.$nextTick(() => { document.querySelector('form.withBackAfterSave').submit() });
}
}">
<input name="backAfterSave" x-bind:value="backAfterSaveStatus">
<div>
<span>
<button x-on:click.prevent="backAfterSave()" type="submit">
Save & back
</button>
</span>
<span>
<button type="submit">
Save
</button>
</span>
</div>
</div>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With