Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binded input value does not appear in request

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);
}
like image 681
keizah7 Avatar asked Nov 22 '20 12:11

keizah7


Video Answer


1 Answers

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>
like image 144
IGP Avatar answered Oct 05 '22 09:10

IGP