How to disable button on click with AlpineJS

Jian Jye
2 min readJan 8, 2021

--

Photo by Jeremy Bishop on Unsplash

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:

  1. We initialize the variable buttonDisabled to be false.
  2. We make it such that when the button is clicked, we’ll set buttonDisabled to be true.
  3. We make it such that the button’s disabled attribute is conditionally triggered based on the buttonDisabled 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>

--

--

Jian Jye

I write about Laravel, PHP, and web development related articles.