Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
charliesneath opened this issue Nov 18, 2024 · 1 comment
Open

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

charliesneath opened this issue Nov 18, 2024 · 1 comment

Comments

@charliesneath
Copy link

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
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants