Alpine JS Tutorial: Delete confirmation

One of the most needed functionality of adding interactivity with Javascript is to show or hide views on demand. To add it with vanilla Javascript is a hassle. So we’ll utilize Alpine JS to do so.

Let’s say you’re making a Todo website and you have the following delete button in your page.

<body>
  <form method="post">
    <button type="submit" class="btn btn-danger">Delete</button>
  </form>
</body>

Your user might have a bad day and accidentally clicked the delete button, his todo will be gone! To prevent that, we want to add confirmation prompt before really deleting the todo. We just need to use AlpineJS for that.

<body>
  <div x-data="{ show: false }">
    <button class="btn btn-danger" @click="show = true">Delete</button>
    <form x-show="show" method="post">
      Are you sure you want to delete?
      <button type="submit" class="btn btn-danger">Delete</button>
      <button type="button" class="btn btn-secondary" @click="show = false">Cancel</button>
    </form>
  </div>
</body>

Data

Alpine JS is a data-focused framework. So usually we initialize it with x-data. We put the important state of our component there. In our case, the component is very small and only has the show state. If it’s true, we show the real form to do delete.

Controlling Visibility

We control the form’s visibility with x-show Alpine property. We then control the state with Alpine @click event. We put the state transition inside.

Complete Code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Alpine js delete confirmation</title>
        <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    </head>

    <body>
        <div x-data="{ show: false }">
            <button class="btn btn-danger" @click="show = true">Delete</button>
            <form x-show="show" method="post">
                Are you sure you want to delete?
                <button type="submit" class="btn btn-danger">Delete</button>
                <button type="button" class="btn btn-secondary" @click="show = false">Cancel</button>
            </form>
        </div>
    </body>
</html>

Conclusion

Using Alpine JS can really shorten your development. Next up:

  1. I will compare this to vanilla JS so you can see the difference.
  2. Make more complex tutorial where the click does not simply set the state.

Stay tuned. If you have any questions or comments, email me

Related
Alpine