imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
666 stars 15 forks source link

submit form using onchange when one of its fields changes #114

Open charliesneath opened 1 week ago

charliesneath commented 1 week ago

The behavior I'm looking for is to async submit a form whenever once of its number inputs changes, and update the HTML accordingly.

The number input itself is being generated programmatically via a Django Rest Framework (DRF) serializer, so I don't have direct access to edit the input specifically (without taking a bunch of extra steps I want to avoid).

I can achieve this with $ajax, but this feels less elegant than having Alpine AJAX do the request for me:

@change="$ajax('/pages/{{ page.id }}/', {
        method: 'PUT',
        body: new FormData(this.form),
        target: 'preview'
    });">

I tried using the follow for the @change event, but this changed the browser URL instead of making an async call:

<form 
    action='/pages/{{ page.id }}/'
    @change="event.target.form.submit()"
    x-target="preview"
    method="PUT">
    {% render_form serializer %} # Inputs are rendered with this component.
</form>

What's the best approach here?

imacrayon commented 1 week ago

I think @change="event.target.form.requestSubmit()"is what you're looking for here. requestSubmit() will handle the form as through you clicked a "submit" button in the HTML. submit() bypasses normal HTML form stuff.