Sometimes, we want to disable a button on click to avoid double-entry submission. This is especially critical on forms that would create new entries when clicked multiple times, we want to prevent that. Here’s where AlpineJS makes things really easy for us.
Assuming that you have already included AlpineJS somewhere on your page:
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.0/dist/alpine.min.js" defer></script>
Next we would have a simple HTML structure as such:
<div>
<button>Save</button>
</div>
To disable the button on click, we’re going to add some AlpineJS magic to this.:
<div x-data="{ buttonDisabled: false }">
<button x-on:click="buttonDisabled = true" x-bind:disabled="buttonDisabled">Save</button>
</div>
What we have here is that:
- We initialize the variable
buttonDisabled
to befalse
. - We make it such that when the button is clicked, we’ll set
buttonDisabled
to betrue
. - We make it such that the button’s
disabled
attribute is conditionally triggered based on thebuttonDisabled
variable.
That’s all!
And if you need multiple buttons that will disable on click, you just need to duplicate the same codes and they will work just fine independently!
<div x-data="{ buttonDisabled: false }">
<button x-on:click="buttonDisabled = true" x-bind:disabled="buttonDisabled">Save</button>
</div><div x-data="{ buttonDisabled: false }">
<button x-on:click="buttonDisabled = true" x-bind:disabled="buttonDisabled">Save 2</button>
</div><div x-data="{ buttonDisabled: false }">
<button x-on:click="buttonDisabled = true" x-bind:disabled="buttonDisabled">Save 3</button>
</div>
JSFiddle: https://jsfiddle.net/pqt6khn2/1/