Confirmation Modal Dialog

A reusable modal component demonstrating dynamic component creation, event handling, and form validation.

Live Demo

Click the button below to open a confirmation modal. You'll need to type the username "John" to confirm deletion.

Delete User 'John'
💡 Hint: Type "John" in the modal to enable deletion

HTML Template

<x-delete-button x-init='{
  "msg": "Are you sure? Type the username to confirm deletion",
  "account": "John"
}'>
  <a href="/delete-user/32" class="delete-button">
    Delete User 'John'
  </a>
</x-delete-button>

JavaScript Components

function DeleteModal(self, href, msg, confirmation) {
  self.confirmation = "";
  self.msg = msg;

  self.close = () => {
    self.remove();
  }

  self.delete = () => {
    if (self.confirmation === confirmation) {
      alert(`Successfully deleted! (Would redirect to: ${href})`);
      self.remove();
    } else {
      alert("Confirmation text doesn't match!");
      self.confirmation = "";
    }
  }

  self.template = `
    <div class="overlay">
      <div class="modal">
        <div class="msg">{{msg}}</div>
        <input type="text"
               value="{{confirmation}}"
               x-enter-pressed="delete"
               placeholder="Type username to confirm" />
        <div class="form-buttons">
          <div class="form-submit cancel" x-click="close">
            Cancel
          </div>
          <div class="form-submit delete" x-click="delete">
            Delete
          </div>
        </div>
      </div>
    </div>`;
}

function DeleteButton(self) {
  const link = self.find('a');

  link.on('click', (e) => {
    e.preventDefault();
    let href = link.getAttribute('href');
    self.append($(DeleteModal, href, self.msg, self.account));
  });
}

$([DeleteButton, DeleteModal]);

Key Concepts