Search code examples
sveltesveltekit

Is there a way to submit a form programatically in SvelteKit using use:enhance


I have a form

<script>
    let form;
    let submitAvatarChangeButton;
</script>


<form 
    bind:this={form}
    method="POST"
    action="?/saveAvatar" 
    enctype="multipart/form-data"
    use:enhance={ async ({ cancel }) => {
        isProcessing = true;

        return async ({ result, update}) => {
            maybeShowError(result);
            isProcessing = false;
            await invalidateAll();
        };
    }
}>
    <!-- Some Input Stuff -->
    <button bind:this={submitAvatarChangeButton} type="submit">Click me</button>
</form>

And then I'm trying to submit this form via:

<button 
    type="button" 
    on:click="() => form.submit()"
>
    Submit the form
</button>

This successfully submits the form, however the use:enhance characteristics is lost - ie the page reloads after submitting. The only way I can get it to work is by:

<button 
    type="button" 
    on:click="() => submitAvatarChangeButton.click()"
>
    Submit the form
</button>

which clicks the button within the form. This seems really hacky. Is there a way to ensure the use:enhance remains enabled when programmatically calling the form submit method?


Solution

  • There is a native function that behaves like a user initiated form submission:
    form.requestSubmit()

    (It can be passed the button to use, in case it's relevant.)


    Alternatively, submit buttons can also live outside the form they are supposed to submit and define a form attribute pointing to the ID of the form, no JS required.