How to disable button on click with AlpineJS
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
buttonDisabledto befalse. - We make it such that when the button is clicked, we’ll set
buttonDisabledto betrue. - We make it such that the button’s
disabledattribute is conditionally triggered based on thebuttonDisabledvariable.
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/
