Submit a HTML Form with Alpine.js
I recently had to update an existing code base as part of a major e-commerce refresh. While working on the checkout, we needed to make some UX improvements for mobile users.
One of those changes was to move the different delivery methods into a dropdown box. After choosing a delivery method, we needed to submit the form to update the users basket. Thankfully, Alpine.js makes this too easy.
Using x-ref
x-ref
and the $refs
property are a way of essentially tagging a DOM element within your component. That element can then be manipulated from any of your event handlers. Here is the official example.
<div x-ref="foo"></div><button x-on:click="$refs.foo.innerText = 'bar'"></button>
The Solution
In my case, I needed to submit a form once a user had made a selection. We were only freshening up a project, so I couldn't just switch to using REST API calls.
As I said, Alpine fortunately made this simple. Here is what I came up with.
<form x-ref="myForm">
<select x-on:input="$refs.myForm.submit()">
<option value=""></option>
...
</select>
</form>
You can see I've added the x-ref
attribute to the form. This means I can now access that form DOM element from anywhere within the Alpine component. Then I added an event handler to my dropdown list of delivery methods. x-on:input
is run once a user makes a selection. This submits the form thanks to $refs.myForm.submit()
.