Skip to content

Instantly share code, notes, and snippets.

@newtonjob
Created February 2, 2026 08:12
Show Gist options
  • Select an option

  • Save newtonjob/699baebc5f7e5a26bdbebe220b01854f to your computer and use it in GitHub Desktop.

Select an option

Save newtonjob/699baebc5f7e5a26bdbebe220b01854f to your computer and use it in GitHub Desktop.
Form plugin for Alpine.js
document.addEventListener('alpine:init', () => {
Alpine.magic('form', el => () => {
return Alpine.reactive({
processing: false,
recentlySuccessful: false,
errors: {},
submit() {
return axios.post(el.action, el).then(response => {
this.errors = {};
this.recentlySuccessful = true;
this.dispatch('success', response.data);
setTimeout(() => this.recentlySuccessful = false, 3000);
return Promise.resolve(response.data);
}).catch(({ response }) => {
this.dispatch('error', response);
this.errors = response.data.errors ?? {};
return Promise.reject(response);
}).finally(() => this.dispatch('finish'));
},
dispatch(event, data) {
el.dispatchEvent(new CustomEvent(event, { detail: data, bubbles: true }));
},
});
});
});
@newtonjob
Copy link
Author

Usage

<form
    action="/profile"
    x-data="{ form: $form() }"
    @submit.prevent="form.submit()"
    @success="..."
>
    @method('patch')

    <input name="name">
    <p x-text="form.errors.name" class="text-red-500"></p>

    <input name="email" type="email">
    <p x-text="form.errors.email" class="text-red-500"></p>
    
    <button type="submit" :disabled="form.processing">
        Submit
    </button>
</form>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment